我有以下对象,
public class Pair {
private int row;
private int col;
public Pair(int row, int col){
this.row = row;
this.col = col;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
}
}
Run Code Online (Sandbox Code Playgroud)
我将这些对存储在一个队列中,但是不想检查Queue是否已包含该对.这是我的代码.
Queue<Pair> queue = new LinkedList<>();
if(!queue.contains(new Pair(curr.getRow(), curr.getCol()){
//do something
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,Queue正在存储重复值.有人可以帮助我理解为什么以及解决它的方法是什么?
你没有压倒一切,Object.equals(Object)所以你只能获得参考身份的平等.你需要添加类似的东西
@Override
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair other = (Pair) o;
return row == other.row && col == other.col;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
并且每当你覆盖equals它时强烈建议你也覆盖Object.hashCode()(HashSet例如使用s)
@Override
public int hashCode() {
return Integer.hashCode(row) + Integer.hashCode(col);
}
Run Code Online (Sandbox Code Playgroud)
最后,您也可以覆盖,Object.toString()以便您可以Pair轻松地显示这些内容.就像是,
@Override
public String toString() {
return String.format("Pair: (%d, %d)", row, col);
}
Run Code Online (Sandbox Code Playgroud)