Better way to detect HashMap contains the same List or not

Jason :

I have a List which will be changed overtime and I want to store it with a time value and check if the same List appears again.

ex:

[1, 2, 3] is same as [1, 2, 3]

I thought that since List<Integer> is passed by the reference value, so I think the key should be stringified to be used.

E.g.:

Map<String, Integer> = new HashMap<>()
(key:"stringified key", value: .....)

But I find that Map<List<Integer>, Integer> map = new HashMap<>() also works but I don't know why it works, since the key should be reference to the same list no matter what the values in list changed.

E.g.:

(key:[reference to key], value: .....)
List<Integer> testList = new ArrayList<>();
testList.add(0);
map.put(testList, 0);
testList.set(0, 1);
if(map.containsKey(testList))System.out.println("duplicate");
else System.out.println("unique");

The above result will print "unique" but I think it should print "duplicate". Why does the above result show this?

Karol Dowbecki :

Since yoy changed the content of the ArrayList the value of the ArrayList hashCode also changed.

List<Integer> l = new ArrayList<>();
l.add(0); 
System.out.println(l.hashCode()); // 31
l.set(0, 1);
System.out.println(l.hashCode()); // 32

This goes against the principle of HashMap where the hashCode is used to find the element's location. Objects used for the HashMap keys should have constant hashCode, otherwise the HashMap lookup logic won't work.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=89573&siteId=1