-1

pieces instance is a List that contains class Piece. Piece object contains two instance variables that resemble coordinate int x and int y. However, when I tried these methods, the second method does not return true if the parameter piece is already inside the pieces object. I have generated an equal method on the class Piece. not sure why the second method does not work.

 public boolean alreadyContainsCoordinate1(Piece piece) {
        for (int i = 0; i < getLength(); i++) {
            if (pieces.get(i).getX() == piece.getX() && pieces.get(i).getY() == piece.getY()) {
                return true;
            }
        }

        return false;
    }

    public boolean alreadyContainsThisCoordinate2(Piece piece) {
         for (Piece body : pieces) {
            if (body.equals(piece)) {
                return true;
            }
        }
        return false; 
    }
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

1

Your second alreadyContainsThisCoordinate2() method is probably using the default equals() method for objects, which compares references, not the contents of your particular object. You may try to override equals as follows:

@Override
public boolean equals(Object o) {
    if (!(o instanceof Piece)) {
        return false;
    }

    Piece p = (Piece)o;
    return this.getX() == p.getX() && this.getY() == p.getY();
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I'm using intellij so I use the auto generate. it does create an override method like that. –  Jun 13 '18 at 01:59
  • @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Piece piece = (Piece) o; return x == piece.x && y == piece.y; } –  Jun 13 '18 at 01:59
  • @randomNameGenerator Then I see no reason why your second method should be failing. Try to make your question more reproducible so we have more to go by. – Tim Biegeleisen Jun 13 '18 at 02:00