java - 当两个引用变量引用具有相同 hashCode 的同一个对象时,== 返回 false [toString()] 背后的逻辑是什么?
问题描述
==
当两个引用变量引用具有相同哈希码值的同一个对象时,返回 false背后的逻辑是什么?
public class One {
public static void main(String[] args) {
One o = new One();
One o1 = o;
System.out.println(o.toString());
System.out.println(o1.toString());
System.out.println(o.hashCode());
System.out.println(o1.hashCode());
// Why does it print false ?
System.out.println(o.toString()==o1.toString()); // false
System.out.println(o.hashCode()==o1.hashCode()); // true
System.out.println(o.equals(o1)); // true
System.out.println(o.toString().hashCode()==o.toString().hashCode()); // true
}
}
解决方案
该行与
System.out.println(o.toString()==o1.toString()); // false
有一个toString()
。每个都toString()
创建一个新的字符串对象,它们是具有自己内存位置的不同对象。所以==
实际上检查了这些新字符串对象之间的内存地址。
始终将字符串与 进行比较String#equals
,而不是与进行比较==
。
推荐阅读
- javascript - 如何使用每个函数 jquery 在两个相同的类名上添加一个类?
- java - Search View Recycler View 搜索过滤器在 android 中无法正常工作
- artifactory - 神器升级后用户登录问题(5.5.1->6.23.13)
- python - np.cumsum(input) 的长度比输入数组长——这怎么可能?
- excel - 如何根据来自两个不同 Excel 工作表匹配的两个单元格返回整行?
- javascript - 如何设置 react-multi-select-component 的箭头样式?
- reactjs - 尝试导入错误:“initializeApp”未从“firebase”导出(导入为“firebase”)
- javascript - 如何实现像console.log这样的对象序列化
- python - 如何使用 selenium python 从下面的 HTML 中获取文本属性
- c - mod操作员的困难