javadata-structureshashmap

What is the correct syntax for creating a HashMap in Java?


I've seen two different ways of creating a HashMap:

First way:

Map<Type, Type> map = new HashMap<>();

Note: This one requires to import java.util.Map;

Second way:

HashMap<Type, Type> map = new HashMap<Type, Type>();

I've only used the second one for practice exercises, however, I'd like to understand the differences in both cases, if there is any.


Solution

  • In java 7, the diamond was introduced.

    You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.

    Map<String, List> a = new HashMap<>();

    So, they are technically the same with a later compiler, but it is always recommended to use the second method especially for those who are learning as it is considered a good typesafe practice.

    You can also check https://www.javatpoint.com/diamond-operator-in-java.

    As for map and hashmap, map is just an interface type which describes that it is a set of key, value pairs. Hashmap is an implementation of this.