Java:我的HashMap查找失败,因为它通过REFERENCE,而不是VALUE。我该如何解决?

时间:2018-04-26 19:36:38

标签: hashmap key hashcode value-type

我使用包含3个整数的结构作为我的地图的关键字。看来我的HashMap正在查找基于REFERENCE的键,而不是基于VALUE的键。 有没有办法来解决这个问题? 下面,我期待b和d为真!

public class Triple{
    public int kid;
    public int x;
    public int y;
    public Triple(int a, int b, int c){
        kid=a;
        x=b;
        y=c;
    }

    public Triple(Triple notAcopy, int next, boolean reverse){
        kid=notAcopy.kid;
        x=notAcopy.x + next;
        if (reverse)
            y=notAcopy.y-next;
        else
            y=notAcopy.y+next;
    }

    public String toString(){
        return "("+kid+", "+x+", "+y+") ";
    }
}

    HashMap<Triple, Boolean> forward;
    forward = new HashMap<Triple, Boolean>();
    Triple a = new Triple(1,4,10);
    Triple b = new Triple(1,4,10);
    Triple c = new Triple(1,5,11);
    Triple d = new Triple(1,5,11);
    forward.put(a, true);
    forward.put(c, true);

    System.out.println("a\t"+forward.containsKey(a));
    System.out.println("b\t"+forward.containsKey(b));
    System.out.println("c\t"+forward.containsKey(c));
    System.out.println("d\t"+forward.containsKey(d));

Output:
a   true
b   false
c   true
d   false

2 个答案:

答案 0 :(得分:2)

在Triple类中覆盖hashcode和equals。

答案 1 :(得分:0)

后人: 感谢Timir。这修好了

For those reading at home, this fixed it
@Override
public int hashCode(){
    return kid & x & y;
}

@Override
public boolean equals(Object o){
    Triple t = (Triple) o;
    boolean result = true;
    if (kid != t.kid || x != t.x || y != t.y)   result = false;
    return result;
}