mryan
mryan

Reputation: 402

How to instantiate a collection in Java using Generics?

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

Answers (3)

GETah
GETah

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

Desmond Zhou
Desmond Zhou

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

Jon Newmuis
Jon Newmuis

Reputation: 26530

The latter:

Set<String> myStringSet = new HashSet<String>();

See the Java documentation on generic types for more information.

Upvotes: 5

Related Questions