8

Should the declaration of a HashMap always include the type e.g.

private HashMap<String, String> test = new HashMap<String, String>();

because I see lots of examples in books where <String, String> is left out so we just have something like:

private Map test= new HashMap();

Which one is 'correct'?

3 Answers 3

12

It should really look like

private Map<String, String> test = new HashMap<>();

So elements of both are correct.;) Map is the interface, which defines behavior, and HashMap is an implementation that provides the behavior.

If you want stronger type safety, you should use the generic arguments. While they are not strictly necessary, they add a lot of value at reducing application errors. Since generics were introduced in Java 5, examples from before then won't have show the generic arguments.

The "diamond operator" <> was introduced with Java 7 - it means you can reduce the second occurrence of the generic type specifier to just <>.

Sign up to request clarification or add additional context in comments.

2 Comments

Just to make a note, if you are using jdk1.4 or older, generics won't work. So for legacy code you cannot use generics. You can verify it by using javac -source 1.4 file_name.java.
Bhushan good clarification. I mean to imply that in my 'generics introduced in Java 5' sentence.
8

Since Java 5, the best option has been to use generics with the <> brackets. This lets you know what types the Map uses for key and value, and performs some compile-time checks to prevent you from adding the incorrect types. It also makes it so you don't have to cast values to the correct type when you get them from the map.

If you want to allow all classes for key and value, you can use the <?, ?> generic declaration. But it's almost always best to be as specific as necessary on your generic types.

Also, it is possible to circumvent the generic checks, but they're definitely better than nothing.

Comments

2

Both are correct. Generics have been part of the JDK since version 5. The other code you see might have been written before 5 or intended to be backwards compatible.

Generics have the advantage of giving compile-time enforcement of types and frees you from having to cast.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.