Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a collection in Java using Generics?

Tags:

java

Whats the best way:

Set<String> myStringSet = new HashSet();

Or

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

None of the above?

Does it matter?

like image 552
mryan Avatar asked Dec 13 '11 23:12

mryan


People also ask

Can you instantiate a generic type?

Only reference types can be used to declare or instantiate a generic class. int is not a reference type, so it cannot be used to declare or instantiate a generic class.

Is it a good idea to use generics in collections?

Code that uses generics has many benefits over non-generic code: Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

How do you declare a generic class in Java?

The declaration of a generic class is almost the same as that of a non-generic class except the class name is followed by a type parameter section. The type parameter section of a generic class can have one or more type parameters separated by commas.


2 Answers

The latter:

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

See the Java documentation on generic types for more information.

like image 137
Jon Newmuis Avatar answered Sep 19 '22 13:09

Jon Newmuis


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>.
like image 28
Desmond Zhou Avatar answered Sep 18 '22 13:09

Desmond Zhou