5

Whats the best way:

Set<String> myStringSet = new HashSet();

Or

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

None of the above?

Does it matter?

mryan
  • 362
  • 1
  • 4
  • 17

3 Answers3

5

The latter:

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

See the Java documentation on generic types for more information.

Jon Newmuis
  • 24,486
  • 2
  • 47
  • 56
  • 1
    Just start using the untyped version...when you realize all of the annoying casts you have to do, you'll start using typed Collections! – James Bassett Dec 14 '11 at 01:07
3

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>.
Desmond Zhou
  • 1,349
  • 11
  • 18
0

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.

GETah
  • 20,414
  • 7
  • 55
  • 100