Java HashMap example to avoid collision

I use HashMap in java to store the key and Object <Key,Object> . And I read about the hashmap collision, and I try to avoid this using a linked list.

I did a search on the Internet, but could not find an example of how to do this.

Can someone point me to online resources that implement a hash map with a linked list?

+6
source share
2 answers

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; } } 
+6
source

A collision occurs only if you use the same object as a key or another object as keys with the same hash code and equal .

To use HashMap correctly, you must correctly implement the hashCode and equals method in your key class. Read the property documentation and this article .

If you want to save more than one object by key, you must create a HashMap from the list.

This is a simple example:

 HashMap<Object, List<Object>> map = new HashMap<Object, List<Object>>(); map.put(key, new LinkedList<Object>); map.get(key).add(object); 
+4
source

All Articles