Why does using Collections.emptySet() with generics work in assignment but not as a method parameter

Posted by Karl von L on Stack Overflow See other posts from Stack Overflow or by Karl von L
Published on 2010-06-17T13:05:01Z Indexed on 2010/06/17 13:13 UTC
Read the original article Hit count: 317

Filed under:
|
|

So, I have a class with a constructor like this:

public FilterList(Set<Integer> labels) {
    ...
}

and I want to construct a new FilterList object with an empty set. Following Joshua Bloch's advice in his book Effective Java, I don't want to create a new object for the empty set; I'll just use Collections.emptySet() instead:

FilterList emptyList = new FilterList(Collections.emptySet());

This gives me an error, complaining that java.util.Set<java.lang.Object> is not a java.util.Set<java.lang.Integer>. OK, how about this:

FilterList emptyList = new FilterList((Set<Integer>)Collections.emptySet());

This also gives me an error! Ok, how about this:

Set<Integer> empty = Collections.emptySet();
FilterList emptyList = new FilterList(empty);

Hey, it works! But why? After all, Java doesn't have type inference, which is why you get an unchecked conversion warning if you do Set<Integer> foo = new TreeSet() instead of Set<Integer> foo = new TreeSet<Integer>(). But Set<Integer> empty = Collections.emptySet(); works without even a warning. Why is that?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics