2

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?

Zeus
  • 2,213
  • 8
  • 28
  • 45

2 Answers2

6

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 HashSets 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 Pairs easily. Something like,

@Override
public String toString() {
    return String.format("Pair: (%d, %d)", row, col);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

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

Community
  • 1
  • 1