如果兩個相同的String
實際上不完全相同,那麼爲什麼我可以使用字符串作爲HashMap
中的鍵而不使用相同的String
對象?爲什麼我可以使用字符串作爲HashMap中的鍵?
String s1 = "Test";
String s2 = "Test";
System.out.println(s1 == s2); // should be false
System.out.println(s1.equals(s2)); // should be true
HashMap<String, String> map = new HashMap();
map.put(s1, "foo");
System.out.println(map.get(s2)); // should be "foo"--but why?
是否HashMap
有String
對象的一些特殊行爲?如果沒有,爲什麼可以使用兩個「不同的」字符串來放置並從散列中獲取值?
請注意,由於字符串內聯,'s1 == s2'將爲'true'。 – 2012-02-23 23:37:21
那麼爲什麼使用'.equals()'比較'String'的標準做法? – 2012-02-23 23:40:13
@Ted Hopp s1 == s2將由於*常量池*而成立。 – EJP 2012-02-23 23:42:50