Java中的多值哈希表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1049833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multi-valued hashtable in Java
提问by
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?
哈希表中的同一个键可以有多个值吗?如果没有,你能建议任何可以使用的类或接口吗?
回答by Michael Myers
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.
但是,Map<YourKeyObject, List<YourValueObject>>
如果列表不存在,您可以使用 a和一些实用程序方法来创建列表,或者使用类似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 exactequivalent 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).
请注意,这Multimap
并不完全等同于自制解决方案;Hashtable
同步它的所有方法,但Multimap
不做这样的保证。这意味着如果您在多个线程上使用 aMultimap
可能会导致问题。如果您的地图仅在一个线程上使用,则没有任何区别(您应该一直使用而不是无论如何)。HashMap
Hashtable
回答by Eric
Values of a hash table is Object so you can store a List
哈希表的值是对象,因此您可以存储列表
回答by Mark Renouf
You need to use something called a MultiMap. This is not strictly a Map however, it's a different API. It's roughly the same as a Map<K, List<V>>, but you wont have methods like entrySet() or values().
您需要使用称为MultiMap 的东西。然而,这不是严格意义上的 Map,而是不同的 API。它与 Map<K, List<V>> 大致相同,但您不会使用 entrySet() 或 values() 之类的方法。
回答by luiscubal
Simple. Instead of
Hashtable<Key, Value>
, use Hashtable<Key, Vector<Value>>
.
简单的。而不是
Hashtable<Key, Value>
,使用Hashtable<Key, Vector<Value>>
。
回答by Carl Manaster
See the Google Collections Libraryfor multimaps and similar such collections. The built-in collections don't have direct support for this.
有关多地图和类似的集合,请参阅Google 集合库。内置集合对此没有直接支持。
回答by Jonik
As others pointed out, no. Instead, consider using a Multimap
which can map many values for the same key.
正如其他人指出的那样,没有。相反,请考虑使用Multimap
可以为同一个键映射多个值的a 。
The Google Collections(update: Guava) library contains one implementation, and is probably your best bet.
在谷歌集合(更新:番石榴)库包含一个实现,并可能是你最好的选择。
Edit: of course you can do as Eric suggests, and store a Collection as a value in your Hashtable (or Map, more generally), but that means writing unnecessary boilerplate code yourself. When using a library like Google Collections, it would take care of the low-level "plumbing" for you. Check out this nice exampleof how your code would be simplified by using Multimap instead of vanilla Java Collections classes.
编辑:当然,您可以按照Eric 的建议进行操作,并将 Collection 作为值存储在您的 Hashtable(或更一般的 Map)中,但这意味着您自己编写不必要的样板代码。当使用像 Google Collections 这样的库时,它会为你处理低级的“管道”。查看这个很好的示例,了解如何通过使用 Multimap 而不是普通的 Java Collections 类来简化您的代码。
回答by kdgregory
Rather than give yet another multipmap answer, I'll ask why you want to do this?
而不是给出另一个 multipmap 答案,我会问你为什么要这样做?
Are the multiple values related? If yes, then it's probably better that you create a data structure to hold them. If no, then perhaps it's more appropriate to use separate maps.
多个值是否相关?如果是,那么最好创建一个数据结构来保存它们。如果不是,那么使用单独的地图也许更合适。
Are you keeping them together so that you can iterate them based on the key? You might want to look for an alternative indexing data structure, like a SkipList.
您是否将它们放在一起以便您可以根据密钥对其进行迭代?您可能想要寻找替代索引数据结构,例如 SkipList。
回答by bendin
What you're looking for is a Multimap. The google collections apiprovides a nice implementation of this and much else that's worth learning to use. Highly recommended!
回答by Bill K
None of the answers indicated what I would do first off.
没有一个答案表明我首先会做什么。
The biggest jump I ever made in my OO abilities was when I decided to ALWAYS make another class when it seemed like it might be even slightly useful--and this is one of the things I've learned from following that pattern.
我在面向对象能力方面取得的最大飞跃是当我决定始终创建另一个类时,它看起来甚至可能有点用处——这是我从遵循该模式中学到的东西之一。
Nearly all the time, I find there is a relationship between the objects I'm trying to place into a hash table. More often than not, there is room for a class--even a method or two.
几乎所有的时间,我都发现我试图放入哈希表的对象之间存在关系。通常情况下,有一个课程的空间——甚至是一两个方法。
In fact, I often find that I don't even want a HashMap type structure--a simple HashSet does fine.
事实上,我经常发现我什至不想要一个 HashMap 类型的结构——一个简单的 HashSet 就可以了。
The item you are storing as the primary key can become the identity of a new object--so you might create equals and hash methods that reference only that one object (eclipse can make your equals and hash methods for you easily). that way the new object will save, sort & retrieve exactly as your original one did, then use properties to store the rest of the items.
您作为主键存储的项目可以成为新对象的标识——因此您可以创建仅引用该对象的equals 和hash 方法(eclipse 可以轻松地为您创建equals 和hash 方法)。这样,新对象将完全按照原始对象进行保存、排序和检索,然后使用属性来存储其余项目。
Most of the time when I do that, I find there are a few methods that go there as well and before I know it I have a full-fledged object that should have been there all along but I never recognized, and a bunch of garbage factors out of my code.
大多数时候,当我这样做时,我发现也有一些方法可以使用,在我知道它之前我有一个完整的对象,它应该一直存在但我从未认出,还有一堆垃圾我的代码中的因素。
In order to make it more of a "Baby step", I often create the new class contained in my original class--sometimes I even contain the class within a method if it makes sense to scope it that way--then I move it around as it becomes more clear that it should be a first-class class.
为了使它更像一个“婴儿步骤”,我经常创建包含在我原来的类中的新类——有时我什至将类包含在一个方法中,如果这样定义它的范围是有意义的——然后我移动它随着越来越清楚它应该是一流的。
回答by coobird
In a hashtable, one would use a key/value pair to store information.
在哈希表中,可以使用键/值对来存储信息。
In Java, the Hashtable
class accepts a single value for a single key. The following is an example of an attempt to associate multiple values to a single key:
在 Java 中,Hashtable
该类接受单个键的单个值。以下是尝试将多个值关联到单个键的示例:
Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put("Answer", "42");
ht.put("Hello", "World"); // First value association for "Hello" key.
ht.put("Hello", "Mom"); // Second value association for "Hello" key.
for (Map.Entry<String, String> e : ht.entrySet()) {
System.out.println(e);
}
In an attempt to include multiple values ("World"
, "Mom"
) to a single key ("Hello"
), we end up with the following result for printing the entries in the Hashtable
:
为了将多个值 ( "World"
, "Mom"
) 包含到单个键 ( "Hello"
) 中,我们最终得到以下结果以打印 中的条目Hashtable
:
Answer=42
Hello=Mom
The key/value pair of "Hello"
and "World"
is not in the Hashtable
-- only the second "Hello"
and "Mom
" entry is in the Hashtable
. This shows that one cannot have multiple values associate with a single key in a Hashtable
.
"Hello"
and的键/值对"World"
不在Hashtable
- 只有第二个"Hello"
和 " Mom
" 条目在Hashtable
. 这表明不能将多个值与Hashtable
.
What is really needed here is a multimap, which allows an association of multiple values to a single key.
这里真正需要的是multimap,它允许将多个值关联到单个键。
One implementation of the multimap is Multimap
from Google Collections:
multimap 的一种实现Multimap
来自Google Collections:
Multimap<String, String> mm = HashMultimap.create();
mm.put("Answer", "42");
mm.put("Hello", "World");
mm.put("Hello", "Mom");
for (Map.Entry<String, String> e : mm.entries()) {
System.out.println(e);
}
This is similar to the example above which used Hashtable
, but the behavior is quite different -- a Multimap
allows the association of multiple values to a single key. The result of executing the above code is as follows:
这类似于上面使用的示例Hashtable
,但行为完全不同——aMultimap
允许将多个值关联到单个键。执行上述代码的结果如下:
Answer=42
Hello=Mom
Hello=World
As can be seen, for the "Hello"
key, the values of "Mom"
and "World"
associated with it. Unlike Hashtable
, it does not discard one of the values and replace it with another. The Multimap
is able to hold on to multiple values for each key.
可以看出,对于"Hello"
键,它的值"Mom"
和"World"
与之相关的值。与 不同Hashtable
,它不会丢弃一个值并将其替换为另一个值。的Multimap
是能够坚持到多个值的每个关键。