String Vs Stringbuffer 作为 HashMap 键

String Vs Stringbuffer as HashMap key(String Vs Stringbuffer 作为 HashMap 键)
本文介绍了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.

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/StringBuilder.java

这篇关于String Vs Stringbuffer 作为 HashMap 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)