Java HashMap already handles conflicts for you this way. All you have to do is make sure that you redefine and apply the hashCode() and equals() keys.
Each hash code will be displayed in a specific bucket. Each bucket contains a linked list for a collision event.
The only way to avoid (or rather minimize) collisions is to create a hash function that creates the best possible distribution of values ββthroughout the HashMap. Depending on the density of your HashMap and the quality of your hash code , collisions are almost inevitable, so two methods need to be redefined.
Edit : OP requested an example
To override two methods:
public class MyObject { String var1; int var2; //... public boolean equals(Object obj) { if(obj == null) return false; if(this == obj) return true; // Reference equality if(!(obj instanceof MyObject)) return false; MyObject myObj = MyObject(obj); return (var1.equals(myObj.var1)) && (var2 == myObj.var2); } public int hashCode { return var1.hashCode() ^ var2; } }
source share