Java HashMap with or without type?

If a HashMap declaration always includes a type, for example.

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

because I see a lot of examples in books where <String, String> missing, so we have something like:

 private Map test= new HashMap(); 

Which one is "correct"?

+6
source share
3 answers

It really should look like

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

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

If you need stronger security, you should use general arguments. Although not strictly necessary, they add more value to reduce application errors. Since generics were introduced in Java 5, the examples from earlier will not show general arguments.

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

+9
source

Starting with Java 5, the best option was to use generics with parentheses <>. This allows you to find out what types Map uses for the key and value, and performs some compile-time checks to prevent the addition of the wrong types. It also makes it so that you do not need to enter values ​​in the correct type when you get them from the map.

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

You can also get around general checks, but they are definitely better than nothing.

+5
source

Both are correct. Generics have been part of the JDK since version 5. The other code that you see could be written before 5 or intended for backward compatibility.

Generics have the advantage of being able to compile time types and freeing you from doing things.

+1
source

Source: https://habr.com/ru/post/888089/


All Articles