为什么会发生这种情况,我该如何避免?我假设它只检查引用,但这不是很方便。
import java.util.LinkedHashMap;
public class CheckingLinkedHashMap {
public static void main(String[] args) {
LinkedHashMap<String[], String[]> linkedh = new LinkedHashMap<>();
String[] a = "A".split(",");
String[] ab = "A,B".split(",");
linkedh.put(a, ab);
String[] aa = "A".split(",");
String[] aabb = "A,B".split(",");
System.out.println("Contains key: " + linkedh.containsKey(aa));
System.out.println("Contains value: " + linkedh.containsValue(aabb));
System.out.println("Contains key: " + linkedh.containsKey(a));
System.out.println("Contains value: " + linkedh.containsValue(ab));
}
}
--
Contains key: false
Contains value: false
Contains key: true
Contains value: true
更新
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class CheckingLinkedHashMap {
public static void main(String[] args) {
LinkedHashMap< List<String>, List<String>> linkedh = new LinkedHashMap<>();
String[] a = "A".split(",");
String[] ab = "A,B".split(",");
List<String> al = Arrays.asList(a);
List<String> abl = Arrays.asList(ab);
linkedh.put(al, abl);
String[] aa = "A".split(",");
String[] aabb = "A,B".split(",");
List<String> aal = Arrays.asList(aa);
List<String> aabbl = Arrays.asList(aabb);
linkedh.put(aal, aabbl);
String[] aaa = "A,B".split(",");
String[] aaabbb = "A,B".split(",");
List<String> aaal = Arrays.asList(aaa);
List<String> aaabbbl = Arrays.asList(aaabbb);
linkedh.put(aaal, aaabbbl);
String[] aaaa = "B,A".split(",");
String[] aaaabbbb = "A,B".split(",");
List<String> aaaal = Arrays.asList(aaaa);
List<String> aaaabbbbl = Arrays.asList(aaaabbbb);
linkedh.put(aaaal, aaaabbbbl);
Iterator it = linkedh.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry) it.next();
System.out.println("Key : " + pairs.getKey() + " Value : " + pairs.getValue());
}
System.out.println("Contains key: " + linkedh.containsKey(aal));
System.out.println("Contains value: " + linkedh.containsValue(aabbl));
System.out.println("Contains key: " + linkedh.containsKey(al));
System.out.println("Contains value: " + linkedh.containsValue(abl));
}
}
--
Key : [A] Value : [A, B]
Key : [A, B] Value : [A, B]
Key : [B, A] Value : [A, B]
Contains key: true
Contains value: true
Contains key: true
Contains value: true
这似乎可行。我想我必须做一些额外的检查以避免密钥重复。