String Vs Stringbuffer作为HashMap键 [英] String Vs Stringbuffer as HashMap key
问题描述
我想了解为什么String和Stringbuilder / StringBuffer在作为Hashmap键使用时被区别对待。以下插图让我更加清楚:
示例#1,使用字符串:
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'。
<使用StringBuilder(或StringBuffer)的例子#2:
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'。
任何人都可以解释为什么行为有所不同。
StringBuilder / Buffer不会覆盖hashCode和equals。这意味着对象的每个实例都应该是唯一的哈希代码,并且其值或状态不重要。您应该使用字符串作为键。
StringBuilder / Buffer也是可变的,这通常不是一个好主意,因为将它作为HashMap的键存储它可能会导致修改后无法访问该值。
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:
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());
Above code snippet prints '1'.
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());
The above code snippet prints '2'.
Could anyone please explain why the difference in behaviour.
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 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.
这篇关于String Vs Stringbuffer作为HashMap键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!