在Java字典类中,是否可能一个键对应多个值?
首先,关于字典类:该类被认为已经过时,文档建议使用Map代替。
您正在寻找的这种集合被称为multimap。您可以使用列表自己实现一个,但那很繁琐。
您可能想要使用来自Apache Collections或Google Collections的MultiMap。虽然我个人是Apache Collections的粉丝,但它们并不真正支持泛型,因此Google multimap可能更安全。
Map
,并将值设置为Collection
:Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
map.put(0, Arrays.asList("foo", "bar"));
map.put(1, new ArrayList<String>());
map.get(1).add("blag");
或者您可以使用MultiMap
,它是来自Apache Commons Collections的一个工具。
A
MultiMap
is aMap
with slightly different semantics. Putting a value into the map will add the value to aCollection
at that key. Getting a value will return aCollection
, holding all the values put to that key.For example:
MultiMap mhm = new MultiHashMap(); mhm.put(key, "A"); mhm.put(key, "B"); mhm.put(key, "C"); Collection coll = (Collection) mhm.get(key);
coll
will be a collection containing "A", "B", "C".
很遗憾,MultiMap
并没有使用泛型。