开发者

Java HashMap with or without type?

开发者 https://www.devze.com 2023-03-06 07:58 出处:网络
Should the declaration of a HashMap always include the type e.g. private HashMap<String, String> test = new HashMap<String, String>();

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 Ha开发者_StackOverflowshMap();

Which one is 'correct'?


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 <>.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消