問題描述
我試圖理解為什么 String 和 Stringbuilder/StringBuffer 在用作 Hashmap 鍵時會被區(qū)別對待.讓我通過以下插圖更清楚地說明我的困惑:
I am trying to understand why String and Stringbuilder/StringBuffer are treated differently when used as Hashmap keys. Let me make my confusion clearer with the following illustrations:
示例 #1,使用字符串:
Example #1, using String:
String s1 = new String("abc");
String s2 = new String("abc");
HashMap hm = new HashMap();
hm.put(s1, 1);
hm.put(s2, 2);
System.out.println(hm.size());
上面的代碼片段打印1".
Above code snippet prints '1'.
示例 #2,使用 StringBuilder(或 StringBuffer):
Example #2, using StringBuilder(or StringBuffer):
StringBuilder sb1 = new StringBuilder("abc");
StringBuilder sb2 = new StringBuilder("abc");
HashMap hm = new HashMap();
hm.put(sb1, 1);
hm.put(sb2, 2);
System.out.println(hm.size());
上面的代碼片段打印2".
The above code snippet prints '2'.
誰能解釋一下為什么會出現(xiàn)這種行為差異.
Could anyone please explain why the difference in behaviour.
推薦答案
StringBuilder/Buffer 不覆蓋 hashCode 和 equals.這意味著對象的每個實例都應該是唯一的哈希碼,并且它的值或狀態(tài)無關緊要.您應該使用字符串作為鍵.
StringBuilder/Buffer do not override hashCode and equals. This means each instance of the object should be a unique hash code and the value or state of it does not matter. You should use the String for a key.
StringBuilder/Buffer 也是可變的,這通常不是用作 HashMap 的鍵的好主意,因為將值存儲在其下可能會導致修改后無法訪問該值.
StringBuilder/Buffer is also mutable which is generally not a good idea to use as a key for a HashMap since storing the value under it can cause the value to be inaccessible after modification.
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/StringBuilder.java
這篇關于String Vs Stringbuffer 作為 HashMap 鍵的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!