让我们看看这些代码:
HashMap<String, List<String>> testTree = new HashMap<String, List<String>>();
String k = new String("1");
String v = new String("2");
List<String> children = new ArrayList<String>();
children.add(v);
testTree.put(k, children);
if (testTree.containsKey("1")){
System.out.println("found!!");
}
else
System.out.println("No found!!");
输出1:found!!
HashMap<String[], List<String[]>> testTree2 = new HashMap<String[], List<String[]>>();
String[] k2 = {"1","2"};
String[] v2 = {"2","3"};
List<String[]> children2 = new ArrayList<String[]>();
children2.add(v2);
testTree2.put(k2, children2);
String[] k3 = {"1","2"};
if (testTree.containsKey(k3)){
System.out.println("found!!");
}
else
System.out.println("No found!!");
输出2:No found!!
为什么输出 1 是“找到”而输出 2 是“未找到”?这意味着如果键是字符串数组,则 HashMap 无法识别它的键,但如果键是字符串,那么它就可以了。
我需要将一个String数组放入HashMap的key中,那么如何让HashMap识别String数组的key呢?