Created
March 7, 2012 16:17
-
-
Save lowasser/1994139 to your computer and use it in GitHub Desktop.
Maps and mutable keys
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.HashMap; | |
| import java.util.Map; | |
| public class Foo { | |
| static class Mutable { | |
| int value; | |
| Mutable(int value) { | |
| this.value = value; | |
| } | |
| @Override | |
| public int hashCode() { | |
| return value; | |
| } | |
| @Override | |
| public boolean equals(Object obj) { | |
| return obj instanceof Mutable && ((Mutable) obj).value == value; | |
| } | |
| } | |
| public static void main(String[] args) { | |
| Map<Mutable, String> map = new HashMap<Mutable, String>(); | |
| Mutable keyOriginal = new Mutable(1); | |
| Mutable keyCopy = new Mutable(1); | |
| map.put(keyOriginal, "a"); | |
| keyOriginal.value = 3; | |
| System.out.println(map.get(keyCopy)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment