Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 718
Vipul Kumar Avatar asked Nov 29 '25 16:11

Vipul Kumar


2 Answers

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"

like image 119
Amit Bera Avatar answered Dec 02 '25 06:12

Amit Bera


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.

like image 37
Mohammed Deifallah Avatar answered Dec 02 '25 06:12

Mohammed Deifallah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!