gpt4 book ai didi

java - 为什么我可以在 HashMap 中使用字符串作为键?

转载 作者:搜寻专家 更新时间:2023-10-31 08:07:04 32 4
gpt4 key购买 nike

如果两个相同的 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 对象有一些特殊的行为?如果不是,为什么可以使用两个“不同”的字符串来从哈希中放入和获取值?

最佳答案

HashMap 通过调用 equals()hashCode() 来比较对象。
String 覆盖这些方法以按值进行比较。

关于java - 为什么我可以在 HashMap 中使用字符串作为键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9423188/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com