How java HashMap does chaining? how to access all collision values?

前端 未结 5 1747
一个人的身影
一个人的身影 2020-12-11 07:27

I have read somewhere that HashMap uses chaining to resolve collisions. But if that is the case. how can i access all the elements with same key value.

For example :

相关标签:
5条回答
  • 2020-12-11 07:34

    You're obviously looking for a data structure like Guava's MultiMap which allows exactly what you want: Having multiple values per key.

    Java's HashMap does not do chaining, as the documentation for put(K, V) clearly states:

    public V put(K key, V value)

    Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

    0 讨论(0)
  • 2020-12-11 07:40

    HashMap cannot store multiple values for the same key.

    Chaining is used to resolve hash collisions, i.e. situations when different keys have the same hash. So, it's not about storing multiple values with the same key, it's about multiple values whose keys have the same hashes.

    Data structure that can store multiple values for the same key is called a multimap. Unfortunately, there is no built-in implementation of multimap in JRE.

    If you need a multimap, you can maintain a Map of Lists (as suggested by matsev), or use an existing multimap implementation from a third-party library, such as Google Guava.

    See also:

    • Collision resolution
    0 讨论(0)
  • 2020-12-11 07:43

    From the documentation of HashMap.put(K, V):

    Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.

    What you can do is to put a List as your value, e.g.

    HashMap<Integer, List<String>> hmap = new HashMap<Integer, List<String>>();
    List<String> list = hmap.get(1);
    if (list == null) {
        list = new ArrayList<String>();
        hmap.put(1, list);
    }
    list.add("1st value");
    list.add("2nd value");
    // etc
    
    0 讨论(0)
  • 2020-12-11 07:46

    I don't think HashTable allows duplicate keys. You should read this What happens when a duplicate key is put into a HashMap?

    0 讨论(0)
  • 2020-12-11 07:49

    If you store an existing key in the HashMap then it will override the old value with the new value and put() will return the old value

          System.out.println(hmap.put("1",1st value));
          System.out.println(hmap);  // o/p "1st value"
    
    0 讨论(0)
提交回复
热议问题