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?