Skip to content

Instantly share code, notes, and snippets.

@SimonHarmonicMinor
Last active Jun 16, 2020
Embed
What would you like to do?
Person jack = new Person();
jack.setName("Jack");
jack.setAge(23);
Person julia = new Person();
julia.setName("Julia");
julia.setAge(35);
Map<Person, Integer> map = new HashMap<>();
map.put(jack, 35);
map.put(julia, 65);
System.out.println("Map: " + map);
jack.setAge(55); // key corrupting
System.out.println("Corrupted map: " + map);
System.out.println("Jack's rate: " + map.get(jack));
System.out.println("Julia's rate: " + map.get(julia));
@tw-abhi
Copy link

tw-abhi commented Jun 16, 2020

I tried running this code and Jack's rate always returns the value. Can you please check?

@SimonHarmonicMinor
Copy link
Author

SimonHarmonicMinor commented Jun 16, 2020

I tried running this code and Jack's rate always returns the value. Can you please check?

My bad. Person should implement equals and hashCode. The default hashCode implementation returns integer-based point in the memory which is always the same. Even if you change field values. I should have mentioned that in the story. If you use the lombok, try to add @EqualsAndHashCode annotation, or implement those methods by yourself. Thanks for your response!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment