Whats the best way:
Set<String> myStringSet = new HashSet();
Or
Set<String> myStringSet = new HashSet<String>();
None of the above?
Does it matter?
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.
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.
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.
The latter:
Set<String> myStringSet = new HashSet<String>();
See the Java documentation on generic types for more information.
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>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With