0

I am using other posts to work on hashMap Collision handling and people seem to say that the Java HashMap class already has collision handling... It doesnt seem to be working for me!

Is there anyway to make my own collision handling? Heres my code!

            if (result.get(i).containsKey(key)) {
               //collision stuff
            } else {
                result.get(i).put(key,value);
            }
Joseph
  • 1
  • Well,.. The objects you add should have equals() and hashcode() for the set to be able to handle collision : http://tutorials.jenkov.com/java-collections/hashcode-equals.html – cYrixmorten Dec 03 '15 at 16:28

1 Answers1

0

Hashmap (Java) or Hashtable is an algorithm to maps keys to values using a hash function. It creates an index -> buckets internally. This is a method to ensure that a key is uniquely map to a single value to avoid pointing to multiple values.

read here

In your example code, you are checking if the key exists, and should handle the conditions if it does or it doesn't in this case differs with hash maps internal collision handling concept.

daxeh
  • 1,083
  • 8
  • 12
  • so if i use the hashCode() method to develop a key, I shouldnt have to worry about collision, right? – Joseph Dec 03 '15 at 16:42
  • Not exactly, when you create hashCode on a hashmap. It is hash of values in the map for the purpose of comparing ie. h1.hashCode() == h2.hashCode() as equality test. Similarly, every object has a hashCode which Java uses to maintain its unique references, however we compare objects using shallow or deep comparisons by their values and not its hashCode value. – daxeh Dec 03 '15 at 16:52