javahashmapchaininghash-collision

Chaining in HashMap


Code:

public static void main(String[] args) {
    Map<String,String> map= new HashMap<String,String>();
    map.put("a", "s");
    map.put("a", "v");

    System.out.println(map.get("a"));

}

Now, as per my understanding, since the key values in both the put case is the same i.e. a, collision is bound to happen, and hence chaining occurs. [Correct me if I am wrong].

Now if I want to retrieve the list of all the values mapped to key value a, how do i get it?

Right now my println prints v only.


Solution

  • This has nothing to do with collision or chaining: you're replacing the old value of a with a new value.

    A map keeps unique keys. collision/chaining will occur in a hash data structure when two distinct keys happen to get the same hash value based on the particular hash function. Or in java, you can explicitly create an object that returns the same value for hashCode().

    If you want mapping with multiple values for a key, then you'll need to use a different data structure/class.