检查是否包含Java中的对象

时间:2016-03-30 19:39:30

标签: java queue

我有以下对象,

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

我将这些对存储在一个队列中,但是不想检查Queue是否已包含该对。这是我的代码。

Queue<Pair> queue = new LinkedList<>();
if(!queue.contains(new Pair(curr.getRow(), curr.getCol()){
 //do something
}

这不起作用,Queue正在存储重复值。有人可以帮助我理解为什么以及解决它的方法是什么?

2 个答案:

答案 0 :(得分:6)

您不能覆盖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;
}

每当您覆盖equals时,强烈建议您覆盖Object.hashCode()(例如,与HashSet合作),例如

@Override
public int hashCode() {
    return Integer.hashCode(row) + Integer.hashCode(col);
}

最后,您也可以覆盖Object.toString(),以便轻松显示这些Pair。像,

@Override
public String toString() {
    return String.format("Pair: (%d, %d)", row, col);
}

答案 1 :(得分:0)

你应该在你的Pair类中重写equals方法。查看此参考How to override equals method in java

相关问题