You could create your own type and create a bad hash function:
public class BadHash {
private String aString;
public BadHash(String s) {
aString = s;
}
public int hashCode() {
return aString.length();
}
public boolean equals(Object other) {
// boilerplate stuff
BadHash obj = (BadHash) other;
return obj.aString.equals(aString);
}
}
This will make it easy to create a collision.
An example would be:
BadHash a = new BadHash("a", value1);
BadHash b = new BadHash("b", value2);
hashMap.add(a);
hashMap.add(b);
These two entries would collide because a
and b
hash to the same value even though they are not equal.
8
solved Hash collision in Hashmap