简体   繁体   中英

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. 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

@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. Something like,

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

You should override the equals method in you Pair class. Check out this reference How to override equals method in java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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