java - “等于”的错误覆盖?
问题描述
卡在测试象牙上:
class MyKeys {
Integer key;
MyKeys(Integer k) {
key = k;
}
public boolean equals(Object o) {
return ((MyKeys) o).key == this.key;
}
}
这个代码片段:
Map m = new HashMap();
MyKeys m1 = new MyKeys(1);
MyKeys m2 = new MyKeys(2);
MyKeys m3 = new MyKeys(1);
MyKeys m4 = new MyKeys(new Integer(2));
m.put(m1, "car");
m.put(m2, "boat");
m.put(m3, "plane");
m.put(m4, "bus");
System.out.print(m.size());
所以,我的预期输出是“2”,而实际上是 4。我想覆盖 equals 方法的正确性存在一些问题。任何帮助都是有用的。
解决方案
您必须使用“.equals()”而不是“==”来比较对象的键。您还需要根据需要实现 hashCode()。
推荐阅读
- c - C cs50 风格马里奥金字塔中的缩进
- java - Java:从 File 文件夹中读取并将每个添加到 ArrayList
- kubernetes - Kubernetes 工作节点必须具有完全相同的硬件和操作系统
- c# - Task.FromResult 的可空性警告
- php - Woocommerce:如何调试与新订单电子邮件相关的问题?
- python-3.x - 转换为地理数据框时如何确保数据框具有正确的索引
- routes - TYPO3 CMS 9 LTS:PersistedAliasMapper 在不同的 storagePids 中具有相同的 slug
- node.js - 尝试安装 Node 及其相关程序时出错,显然是因为我无法在 Windows 7 中获得 TLS 1.2 支持
- html - 打开菜单时汉堡图标向左移动
- markdown - 如何在我的 Jekyll 页面中包含外部降价文件?