Java 如何使HashMap按预期工作?
假设有一个简单的类:Java 如何使HashMap按预期工作?,java,hashmap,Java,Hashmap,假设有一个简单的类: public class Point implements Comparable<Point> { public int compareTo(Point p) { if ((p.x == this.x) && (p.y == this.y)) { return 0; } else if (((p.x == this.x) && (p.y > this.y))
public class Point implements Comparable<Point> {
public int compareTo(Point p) {
if ((p.x == this.x) && (p.y == this.y)) {
return 0;
} else if (((p.x == this.x) && (p.y > this.y)) || p.x > this.x) {
return 1;
} else {
return -1;
}
}
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
然后人们会做一些类似(琐碎的)事情:
并分别在第一种和第二种情况下获取
true
和false
。发生了什么事?此映射是否比较哈希而不是值?如何使示例在这两种情况下都返回true?由于您使用的是HashMap
,而不是TreeMap
,因此需要在点类中重写hashCode
和等于,而不是比较到
:
@Override
public int hashCode() {
return 31*x + y;
}
@Override
public bool equals(Object other) {
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Point)) return false;
Point p = (Point)other;
return x == p.x && y == p.y;
}
由于您使用的是HashMap
,而不是TreeMap
,因此需要在点
类中重写hashCode
和等于
,而不是比较
:
@Override
public int hashCode() {
return 31*x + y;
}
@Override
public bool equals(Object other) {
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Point)) return false;
Point p = (Point)other;
return x == p.x && y == p.y;
}
非常感谢。另一个问题:如果我重写hashCode
为坐标相等的点返回相同的哈希值,我将无法(假设我确实需要它)区分p1=新点(0,0)
和p2=新点(0,0)
?@cdp始终可以使用引用等式来区分表示等效对象的两个实例。您甚至可以在实例hashmap
中使用它们(这不是一个合适的hashmap,因为它不遵循相同的约定)。谢谢。另一个问题:如果我重写hashCode
为坐标相等的点返回相同的哈希值,我将无法(假设我确实需要它)区分p1=新点(0,0)
和p2=新点(0,0)
?@cdp始终可以使用引用等式来区分表示等效对象的两个实例。您甚至可以在实例HashMap
中使用它们(这不是一个正确的哈希映射,因为它不遵循相同的约定)
@Override
public int hashCode() {
return 31*x + y;
}
@Override
public bool equals(Object other) {
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Point)) return false;
Point p = (Point)other;
return x == p.x && y == p.y;
}