Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can AnyOne Please Explain this HashMap Behaviour

My Program is public class Demo {

public static void main(String[] args) {
    List<String> arr = new ArrayList<>();
    arr.add("a");
    arr.add("b");
    Map<List<String>, String> map = new HashMap<>();
    map.put(arr, "Ravinda");
    System.out.println(map.get(arr));
    arr.add("c");
    System.out.println(map.get(arr));
}

}

Output is: Ravindra and null

I am not able to get why the output of second System.out.println is null.

Can anyone please explain.

like image 832
RAVINDRA PRATAP SINGH Avatar asked Mar 20 '26 21:03

RAVINDRA PRATAP SINGH


1 Answers

When you call: map.put(arr, "Ravinda"); you are setting the key of the "Ravinda" value to be a List containing two strings.

By calling arr.add("c"); you are modifying List used earlier to index the "Ravinda" value in your hashmap.

Since the arr List has been changed, it no longer matches the key specified when you called: map.put(arr, "Ravinda");

This is why the hashmap is returning a null value when you try to access it for the second time.

The hashmap still contains the 'Ravinda' value, but this value is indexed against the list containing only the two values.

like image 105
Guybrush Avatar answered Mar 23 '26 14:03

Guybrush



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!