Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使HashMap按预期工作?_Java_Hashmap - Fatal编程技术网

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;
}