Reputation: 253
Everywhere I look, I see the typing of Collections done like this:
Set<String> set = new HashSet<String>();
However, I define my Collections like this
Set<String> set = new HashSet();
and I still get the type checking (and my way is just cleaner to look at).
Maybe this has something to do when creating generic collections? But, let's say I just want nothing more than a HashSet of Strings, then is not
Set<String> set = new HashSet();
enough?
Upvotes: 0
Views: 5574
Reputation: 122489
In this particular use case, where you are passing no arguments to the constructor, it makes no difference.
However, if you were using a version of the constructor that took a parameter whose type depends on the type variable, then if you use the raw type constructor, the compiler will not check the type properly.
This incorrect code compiles due to the raw type, and will cause heap pollution:
List<Integer> foo = Arrays.asList(1, 2, 3);
Set<String> set = new HashSet(foo);
Whereas using the proper type argument appropriately prevents it from compiling:
List<Integer> foo = Arrays.asList(1, 2, 3);
Set<String> set = new HashSet<String>(foo);
By the way, you can use the diamond operator in Java 7+ if you don't want to be so verbose:
Set<String> set = new HashSet<>();
Upvotes: 1
Reputation: 4090
You are using a generic class when creating a new collection.
The generic class must get the generic type it encapsulates, otherwise it is considered a Raw Type.
The proper declaration of the collection value, should therefore be:
Set<String> mySet = new HashSet<>();
Your JVM will be able to infer the generic type being used in your HashSet thanks to the declaration on Set<String>
Most IDEs (Eclipse and ItelliJ, for example) will have their linters configured to provide a warning when using a Raw Type class. This warning can be suppressed, but that is considered a bad practice.
References:
Bonus:
Upvotes: 7