So, I have a class with the following constructor:
public FilterList(Set<Integer> labels) { ... }
and I want to build a new FilterList object with an empty set. Following the advice of Joshua Bloch in my book Effective Java, I do not want to create a new object for an empty set; I just use Collections.emptySet() instead:
FilterList emptyList = new FilterList(Collections.emptySet());
This gives me an error complaining that java.util.Set<java.lang.Object> not java.util.Set<java.lang.Integer> . OK, how about this:
FilterList emptyList = new FilterList((Set<Integer>)Collections.emptySet());
It 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, so you get a warning about unverified conversions if you do Set<Integer> foo = new TreeSet() instead of Set<Integer> foo = new TreeSet<Integer>() . But Set<Integer> empty = Collections.emptySet(); works even without warning. Why is this?
java collections generics type-inference
Karl von L Jun 17 '10 at 13:05 2010-06-17 13:05
source share