问题描述
如果一个HashMap的键是一个字符串数组:
If a HashMap's key is a string array:
HashMap<String[], String> pathMap;
您可以通过使用一个新创建的字符串数组或是否必须是同一个String []对象?访问地图
Can you access the map by using a newly created string array or does it have to be the same String[] object?
pathMap = new HashMap<>(new String[] { "korey", "docs" }, "/home/korey/docs");
String path = pathMap.get(new String[] { "korey", "docs" });
推荐答案
它必须是相同的对象。 A 的HashMap
比较了使用键的equals()
和Java的两个数组仅当它们是同一个对象相等。
It will have to be the same object. A HashMap
compares keys using equals()
and two arrays in Java are equal only if they are the same object.
如果你想要的值相等,然后写你自己的容器类,包装了一个的String []
,并提供了相应的语义等于()
和散code()
。在这种情况下,这将是最好的,使容器不可改变的,如改变哈希code为对象,基于散列的容器类严重破坏。
If you want value equality, then write your own container class that wraps a String[]
and provides the appropriate semantics for equals()
and hashCode()
. In this case, it would be best to make the container immutable, as changing the hash code for an object plays havoc with the hash-based container classes.
修改
正如其他人所指出的那样,列表与LT;弦乐&GT;
有你似乎想为容器对象的语义。所以,你可以做这样的事情:
As others have pointed out, List<String>
has the semantics you seem to want for a container object. So you could do something like this:
HashMap<List<String>, String> pathMap;
pathMap.put(
// unmodifiable so key cannot change hash code
Collections.unmodifiableList(Arrays.asList("korey", "docs")),
"/home/korey/docs"
);
// later:
String dir = pathMap.get(Arrays.asList("korey", "docs"));
这篇关于可以在Java数组作为一个HashMap的关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!