Java中的多值散列表 [英] Multi-valued hashtable in Java
问题描述
是否可能有一个哈希表中的相同键的多个值?如果没有,你能建议任何这样的类或接口可以使用吗?
这是一个哈希表的想法。
然而,你可以使用 Map< YourKeyObject,List< YourValueObject>
和一些用于创建列表的实用程序方法(如果不存在),或使用类似于 Multimap
.google.com / p / google-collections /rel =nofollow noreferrer> Google Collections 。
示例:
String key =hello;
Multimap< String,Integer> myMap = HashMultimap.create();
myMap.put(key,1);
myMap.put(key,5000);
System.out.println(myMap.get(key)); //打印[1,5000]或[5000,1]
myMap = ArrayListMultimap.create();
myMap.put(key,1);
myMap.put(key,5000);
System.out.println(myMap.get(key)); //总是打印[1,5000]
注意 Multimap
不是一个 exact 等效的自制解决方案; Hashtable
同步其所有方法,而 Multimap
则不提供此类保证。这意味着如果您在多个主题中使用 ,使用 Multimap
可能会导致问题。如果你的地图只在一个线程上使用,它将没有什么区别(你应该使用 HashMap
,而不是 Hashtable
>
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?
No. That's kind of the idea of hash tables.
However, you could either roll your own with a Map<YourKeyObject, List<YourValueObject>>
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<String, Integer> 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).
这篇关于Java中的多值散列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!