有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

具有相同哈希代码的java Equal对象不会映射到HashMap中的相同值

我使用一个自定义类Vec作为HashMap中的键

但是两个具有相同hashCode()的相等Vec对象不会映射到同一个键

我做错了什么

import java.util.HashMap;

/**
 * A 2-element float Vector
 */
class Vec {
    public float x;
    public float y;

    public Vec(float x, float y) {
        this.x = x;
        this.y = y;
    }

    public Vec(Vec v) {
        this.x = v.x;
        this.y = v.y;
    }

    public boolean equals(Vec v) {
        System.out.println("equals called");
        return (x == v.x &&
                y == v.y);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = (Float.floatToIntBits(x)
                      + prime * Float.floatToIntBits(y));
        System.out.println("hash called: " + result);
        return result;
    }
}

public class Debug {
    public static final void main(String[] args) {
        Vec v1 = new Vec(3, 5);
        Vec v2 = new Vec(v1);
        System.out.println("vecs equal: " + v1.equals(v2));
        System.out.println("hashcodes: " + v1.hashCode() + ", " + v2.hashCode());

        System.out.println("\nuse map");
        HashMap<Vec, Object> map = new HashMap<>();
        map.put(v1, new Object());
        Object o1 = map.get(v1);
        Object o2 = map.get(v2);
        System.out.println(o1);
        System.out.println(o2);
        if (o2 == null) {
            throw new RuntimeException("expected o2 not to be null");
        }
    };
}

输出

equals called
vecs equal: true
hash called: 329252864
hash called: 329252864
hashcodes: 329252864, 329252864

use map
hash called: 329252864
hash called: 329252864
hash called: 329252864
java.lang.Object@2a139a55
null
Exception in thread "main" java.lang.RuntimeException: expected o2 not to be null

共 (0) 个答案