String Vs Stringbuffer 作为 HashMap 键
问题说明
我试图理解为什么 String 和 Stringbuilder/StringBuffer 在用作 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:
示例 #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'.
谁能解释一下为什么会出现这种行为差异.
Could anyone please explain why the difference in behaviour.
正确答案
StringBuilder/Buffer 不覆盖 hashCode 和 equals.这意味着对象的每个实例都应该是唯一的哈希码,并且它的值或状态无关紧要.您应该使用字符串作为键.
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.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tangibkeb
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
希伯来语的空格句子标记化错误
it1352 06-22