Search code examples
javadictionaryhashmapreturn-type

What does map.put return?


I tried to get the return type of put method of the map interface. When I print for the first time it is printing null and after updating the key I get the previous value. So, can anyone tell me what is the return type of the put method in the map interface?

Map<Integer, String> map = new HashMap<Integer, String>();
System.out.println(map.put(1, "ABC"));
System.out.println(map.put(1, "XYZ"));

Output:
null
ABC

Solution

  • return type of put method in the map is the value type.

    Method declaration of put: V put(K key, V value);

    Where,

    key: key with which the specified value is to be associated

    value: value to be associated with the specified key

    return type: The previous value associated with the key, or null if there was no mapping for key. A null return can also indicate that the map previously associated null with key if the implementation supports null values.

    For Example -

    System.out.println(map.put(1, "ABC")); --> In this case there is no value associated with the key 1, so it returns null

    System.out.println(map.put(1, "XYZ")); --> When you are storing a new value against an already stored key, the new value will replace the previous value and the put method will return the previous value which was overridden. In this case, it will return ABC.