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
As per java docs:
The put returns the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with the key if the implementation supports null values.)
In your case when you did map.put(1, "ABC") nothing was associated with key 1 so it returns null but when you use put(1, "XYZ") then there was already an entry exists against the key 1 so it returns "ABC"
According to documentation, it's a generic function that returns the same datatype as the map value. So, in your case it should return String.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With