简体   繁体   English

检查Java是否包含对象

[英]Check if a contains an object in Java

I've the following Object, 我有以下对象,

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

I'm storing these pairs in a queue, but wan't to check if the Queue contains the Pair already. 我将这些对存储在队列中,但是不想检查队列中是否已经包含该对。 This is my code. 这是我的代码。

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

This is not working and the Queue is storing duplicate values. 这不起作用,队列正在存储重复的值。 Can someone help mw understand why and what's the way to fix it? 有人可以帮助大众了解原因以及解决方法吗?

You aren't overriding Object.equals(Object) so you get equality only for reference identity. 您没有重写Object.equals(Object)因此仅对引用标识具有相等性。 You need to add something like 您需要添加类似

@Override
public boolean equals(Object o) {
    if (o instanceof Pair) {
        Pair other = (Pair) o;
        return row == other.row && col == other.col;
    }
    return false;
}

and whenever you override equals it's strongly recommended that you override Object.hashCode() as well (to work with HashSet s for example) like 并且无论何时重写equals ,都强烈建议您也重写Object.hashCode() (例如,与HashSet一起使用),例如

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

Finally, you might as well override Object.toString() so you can display these Pair s easily. 最后,您最好覆盖Object.toString()以便可以轻松显示这些Pair Something like, 就像是,

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

You should override the equals method in you Pair class. 您应该在Pair类中重写equals方法。 Check out this reference How to override equals method in java 查阅此参考资料如何在Java中覆盖equals方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM