If you instantiate a new HashSet, you usually use the Set interface to work with it afterwards. Just like
Set<T> set = new HashSet();
So what is the use of specifying the type of the HashSet explicitly, too? For example:
Set<T> set = new HashSet<T>();
I’ve seen it in quite a couple of books, but I can’t think of any use at all. If you need access to the set, you’ll work with the interface (which is already parameterized) anyway.
If you say this:
you’ll get an unchecked conversion warning. The static type of
new HashSet()is a raw HashSet, and converting from that to a generified type is potentially unsafe.There are other circumstances where doing an assignment will cause type inference to take place. Calling a static method is the canonical example. eg:
Java doesn’t do inference on the
newoperator, however, as this would introduce an ambiguity into the language.If you don’t like the redundancy you can use a wrapper static method, and inference will take place. Google’s Guava does this, so you can say: