-1

I have been implementing a hashmap from scratch and this dawned on me.

Lets say I have 3 distinct keys and 3 values

      Keys -> Value:  A -> 1, B -> 2,C -> 3

and they each land in an open slot in the array.

If the fourth key D produces the same hash index as one of the previously 3 keys I can use any of the collision strategies to handle this case (Linear Probing, rehashing, etc )

However lets say I want to overwrite [Key A, Value 1] with [Key A, 99]. This is a collision however Java.Util.HashMap knows you want to overwrite the value.

If a collision occurs, How do you determine whetherto overwrite a value or search for an open location ?

Rstack
  • 45
  • 1
  • 10
  • 1
    I don't understand. If there's a collision, it only means the result of your bucketing/hash function is the same for two keys. It says nothing about whether those two keys are equal. That's what you should check. – Sotirios Delimanolis Feb 13 '17 at 03:16
  • Collision is when two keys map to the same storage location. Overwriting a value is when you want to update the value of a particular key. – David Choweller Feb 13 '17 at 03:16
  • Updating a key is part of the interface of a hashing data structure. Collision handling is part of the implementation. – David Choweller Feb 13 '17 at 03:19
  • If a collision occurs on a `put` operation, you need to iterate over the bucket and if you find a matching key, replace it, otherwise insert a new entry. – shmosel Feb 13 '17 at 03:19

1 Answers1

-2

Here is my answer.
Store the keys in a hashset.
If a collision occurs, check to see if that key is in the set.
If it is replace the value. If not use a collision strategy

Rstack
  • 45
  • 1
  • 10