Reputation: 402
Whats the best way:
Set<String> myStringSet = new HashSet();
Or
Set<String> myStringSet = new HashSet<String>();
None of the above?
Does it matter?
Upvotes: 5
Views: 9906
Reputation: 21449
The second is the best and safest way to proceed.
Set<String> myStringSet = new HashSet();
will compile and give a ...uses unchecked or unsafe operations.
warning. This comes up in Java 5 and later, if you're using collections without generic type specifiers (HashSet()
instead of HashSet<String>()
).
Omitting the generic type specifier will disable the compiler from checking that you're using the HashSet
in a type-safe way, using generics.
Upvotes: 0
Reputation: 1409
You should always initialize collection with generic type
Set<String> myStringSet = new HashSet<String>();
Otherwise you will get a warning
Type safety: The expression of type HashSet needs unchecked conversion
to conform to Set <String>.
Upvotes: 3
Reputation: 26530
The latter:
Set<String> myStringSet = new HashSet<String>();
See the Java documentation on generic types for more information.
Upvotes: 5