Java中的HashMap如何使用equals()和hashCode()查找对象?
我定义了一个Point类,如下所示,覆盖了Java中的HashMap如何使用equals()和hashCode()查找对象?,java,hashmap,equals,Java,Hashmap,Equals,我定义了一个Point类,如下所示,覆盖了equals()和hashCode()。我原以为在main()方法中会打印“Key Found”,但事实并非如此 据我所知,Java使用equals()和hashCode()在HashMap中添加或查找对象。我不确定我在这里做错了什么 import java.util.*; public class Point { int row = 0; int col = 0; public Point(int row, int col) {
equals()
和hashCode()
。我原以为在main()
方法中会打印“Key Found”,但事实并非如此
据我所知,Java使用equals()
和hashCode()
在HashMap
中添加或查找对象。我不确定我在这里做错了什么
import java.util.*;
public class Point {
int row = 0;
int col = 0;
public Point(int row, int col) {
this.row = row;
this.col = col;
}
public String toString() {
return String.format("[%d, %d]", row, col);
}
public boolean equals(Point p) {
return (this.row == p.row && this.col == p.col);
}
public int hashCode() {
return 31 * this.row + this.col;
}
public static void main(String[] args) {
HashMap<Point, Integer> memo = new HashMap<>();
Point x = new Point(1, 2);
Point y = new Point(1, 2);
memo.put(x, 1);
if (x.equals(y))
System.out.println("x and y are equal");
System.out.println("Hashcode x= " + x.hashCode() + " Hashcode y= " +
y.hashCode());
if (memo.containsKey(y)) {
System.out.println("Key found");
}
}
}
output
x and y are equal
Hashcode x= 33 Hashcode y= 33
import java.util.*;
公共课点{
int行=0;
int col=0;
公共点(整数行,整数列){
this.row=行;
this.col=col;
}
公共字符串toString(){
返回字符串。格式(“[%d,%d]”,行,列);
}
公共布尔等于(点p){
返回(this.row==p.row&&this.col==p.col);
}
公共int hashCode(){
返回31*this.row+this.col;
}
公共静态void main(字符串[]args){
HashMap memo=新的HashMap();
点x=新点(1,2);
点y=新点(1,2);
备忘录.付诸表决(x,1);
如果(x等于(y))
System.out.println(“x和y相等”);
System.out.println(“Hashcode x=“+x.Hashcode()+”Hashcode y=“+
y、 hashCode());
如果(备忘录内容(y)){
System.out.println(“找到密钥”);
}
}
}
输出
x和y相等
哈希代码x=33哈希代码y=33
问题在于您实际上没有重写equals()
方法。将对象
作为参数,而不是点
对象。因此,您实现的equals()
方法实际上没有被调用。将@Override
标记添加到您被重写的方法中,它会非常清楚您做错了什么。您是否理解为什么这个方法:public boolean equals(Point p){return(this.row==p.row&&this.col==p.col);}不是您想要的/方式(it),尽管您需要正确重写对象#equals,但请查看文档以获得正确的equals实现。如果另一个点是null
,您将得到一个NullPointerException,尽管x.equals(null)
应该返回false
@TanM没有问题。考虑接受答案。