Multi-valued hashtable in Java

前端 未结 13 2086
余生分开走
余生分开走 2020-12-06 09:41

Is it possible to have multiple values for the same key in a hash table? If not, can you suggest any such class or interface which could be used?

13条回答
  •  我在风中等你
    2020-12-06 10:00

    No. That's kind of the idea of hash tables.

    However, you could either roll your own with a Map> and some utility methods for creating the list if it's not present, or use something like the Multimap from Google Collections.

    Example:

    String key = "hello";
    Multimap myMap = HashMultimap.create();
    myMap.put(key, 1);
    myMap.put(key, 5000);
    System.out.println(myMap.get(key)); // prints either "[1, 5000]" or "[5000, 1]"
    myMap = ArrayListMultimap.create();
    myMap.put(key, 1);
    myMap.put(key, 5000);
    System.out.println(myMap.get(key)); // always prints "[1, 5000]"
    

    Note that Multimap is not an exact equivalent of the home-baked solution; Hashtable synchronizes all its methods, while Multimap makes no such guarantee. This means that using a Multimap may cause you problems if you are using it on multiple threads. If your map is used only on one thread, it will make no difference (and you should have been using HashMap instead of Hashtable anyway).

提交回复
热议问题