Skip to content

Instantly share code, notes, and snippets.

@anandrajneesh
Created April 11, 2017 07:16
Show Gist options
  • Save anandrajneesh/8c8928036b92e5dbca1b7c4ed0e3b462 to your computer and use it in GitHub Desktop.
Save anandrajneesh/8c8928036b92e5dbca1b7c4ed0e3b462 to your computer and use it in GitHub Desktop.
Demonstration - Buggy hashcode can create a havoc in Hashmap
import java.util.HashMap;
import java.util.Map;
/**
* Created by Anand_Rajneesh on 4/3/2017.
*/
public class Demo {
public static void main(String[] args) {
Map<Key,String> map = new HashMap<>();
Key key1 = new Key(10);
Key key2 = new Key(5);
Key key3 = new Key(4);
System.out.println("Key1 hashcode "+key1.hashCode());
System.out.println("Key2 hashcode "+key2.hashCode());
System.out.println("Key3 hashcode "+key3.hashCode());
System.out.println("Key1 equals Key2 ? "+key1.equals(key2));
System.out.println("Key1 equals Key3 ? "+key2.equals(key3));
System.out.println("Key2 equals Key3 ? "+key3.equals(key2));
map.put(key1, "key1");
map.put(key2, "key2");
System.out.println("Map.get key1 "+ map.get(key1));
System.out.println("Map.get key2 "+map.get(key2));
System.out.println("Map.get key3 "+map.get(key3));
map.put(key3, "key3");
System.out.println("Map.get key1 "+map.get(key1));
System.out.println("Map.get key2 "+map.get(key2));
System.out.println("Map.get key3 "+map.get(key3));
}
private static class Key{
private final int id;
public Key(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if(obj != null && obj instanceof Key){
if(id < 10 && ((Key)obj).id < 10){
return true;
}
return id == ((Key)obj).id;
}
return false;
}
@Override
public int hashCode() {
if(id<10)
return 0;
else
return 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment