为什么可以使用字符串作为 HashMap 中的键?
如果两个相同的 String 实际上并不相同,那么为什么我可以使用字符串作为 HashMap 中的键而不使用相同的 String目的?
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
对象是否有一些特殊行为?如果不是,为什么可以使用两个“不同”的字符串来从哈希中放入和获取值?
If two String
s that are the same are not actually identical, then why can I use strings as keys in a HashMap
without using the same String
object?
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?
Does HashMap
have some special behavior for String
objects? If not, why can two "different" strings be used to put and to get values from a hash?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
HashMap
通过调用equals()
和hashCode()
来比较对象。String
重写这些方法以按值进行比较。HashMap
compares objects by callingequals()
andhashCode()
.String
overrides these methods to compare by value.一般来说,您可以使用 String 对象,因为 HashMap 使用
equals()
而不是==
来测试键相等性。In general, you can use String objects because HashMap uses
equals()
and not==
to test for key equality.但它们是相等的。它们在 equals() 方法下相等,这是在 Map 接口中指定的相等测试技术。
但这并不假!由于编译器的常量池,两者都引用相同的字符串。
But they are. They are equal under the equals() method, and that is the technique specified for equality testing in the
Map
interface.But it isn't false! Both refer to the same string because of constant pooling by the compiler.
当
HashMap
内部比较键时,它使用equals()
方法,而不是==
。因此,对象相等对于键匹配来说是很好的,如果覆盖 equals() 则不需要引用相等(如 java.lang.String 的情况)。When the
HashMap
compares the key internally, it uses theequals()
method, not==
. So object equality is fine for a key match, reference equality is not required ifequals()
is overridden (as in the case ofjava.lang.String
.)不应该。 Java编译器可能会优化并将两个字符串指向同一位置。
更新
输出
It should not. Java compiler may optimize and point two strings to the same location.
Update
Output
我们真的应该首先回到基础。
计算机科学基础:
== 比较内存地址(引用)
.equals 比较存储在内存地址
java basic 中的值。整个jvm中只有一份字符串对象的副本
we should really go back to the basic first.
computer science fundamental:
== compares memory address(reference)
.equals compares value stored in the memory address
java basic. there is only one copy of string object across entire jvm