Skip to content

Instantly share code, notes, and snippets.

@SimonHarmonicMinor
Last active June 16, 2020 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimonHarmonicMinor/3fe35f06c4468b3c0e92df84c49b16ab to your computer and use it in GitHub Desktop.
Save SimonHarmonicMinor/3fe35f06c4468b3c0e92df84c49b16ab to your computer and use it in GitHub Desktop.
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

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