Skip to content

Instantly share code, notes, and snippets.

@lowasser
Created March 7, 2012 16:17
Show Gist options
  • Select an option

  • Save lowasser/1994139 to your computer and use it in GitHub Desktop.

Select an option

Save lowasser/1994139 to your computer and use it in GitHub Desktop.
Maps and mutable keys
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