TL; DR:我用自己的“Pair”类对象制作了一个hashmap对象,用作Keys。当我使用hashmap.containsKey(Pair)时,它无法找到密钥。HashMap.containsKey(key)未能找到密钥,将自定义类用作密钥类型
我有一个叫做Pair的类,代码如下所示。它应该是两个物体的容器。第一个对象可以是任何类型,而第二个对象必须是整数。这不是很好的设计,但我用这种方式编码,所以我可以在我的程序中重新使用该类用于其他目的。
import java.util.ArrayList;
public class Pair<L> {
private L left;
private int right;
public Pair(L left, int right) {
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public int getRight() { return right; }
public void ToString() {
System.out.println(left + "," + right);
}
public boolean equals(Pair p) {
return (this.getLeft().equals(p.getLeft()) && this.getRight() == p.getRight());
}
public ArrayList<Pair> neighbors(int rowLimit, int ColumnLimit) {
ArrayList<Pair> neighbors = new ArrayList<Pair>();
Pair neighborL;
Pair neighborR;
Pair neighborU;
Pair neighborD;
if (((int)this.left-1 >= 0)) {
neighborU = new Pair((int)this.left-1, this.right);
// neighborU.ToString();
neighbors.add(neighborU);
}
if ((int)this.left+1 < rowLimit) {
neighborD = new Pair((int)this.left+1, this.right);
// neighborD.ToString();
neighbors.add(neighborD);
}
if ((int)this.right-1 >= 0) {
neighborL = new Pair((int)this.left, this.right-1);
// neighborL.ToString();
neighbors.add(neighborL);
}
if ((int)this.right+1 < ColumnLimit) {
neighborR = new Pair((int)this.left, this.right+1);
// neighborR.ToString();
neighbors.add(neighborR);
}
return neighbors;
}
}
我存储对作为钥匙,一个HashMap是这样的:
Map<Pair, Integer> costSoFar = new HashMap<Pair, Integer>();
costSoFar.put(sLocale, 0);
当我运行下面的线,这是说,如果关键是没有HashMap的:
if (!costSoFar.containsKey(next))
它的计算结果为true,即使我知道钥匙在那里,因为我通过调试进行检查。
如果任何人都可以帮忙清理为什么hashmap不能识别密钥,那将是非常感谢。也许我的平等方法不符合要求?
你实现了hashCode吗? – muzzlator
你实现了'equals()'吗? –
此外,您可能需要将您的equals方法与默认的Object equals方法(Object o)参数vs(Pair p)的方法对齐,请参阅http://tutorials.jenkov.com/java-collections/hashcode-equals.html – muzzlator