Contains always returns false


I'm writing chess game and I got trouble with checking if move is valid.

Long story short, I got Pawn (extends Piece) class that has

 //First element of array represents row, second element of array represents column
 Set<int[]> legalMoves = new HashSet<>();

 void initLegalMoves() {
    if(color == PieceColor.WHITE) {
        legalMoves.add(new int[] {-1, 0});
    } else {
        legalMoves.add(new int[] {1, 0});

Now I got another class MoveValidator that checks, obviously, if the move is valid.

    private boolean isLegalMove(int oldRow, int oldColumn, int newRow, int newColumn){
        int rowDifference = newRow - oldRow;
        int columnDifference = newColumn - oldColumn;

        board.getSelectedTile().getPiece().getLegalMoves().forEach(x -> {
            if(x[0] == rowDifference && x[1] == columnDifference){
                System.out.println("Ok move");
        return board.getSelectedTile().getPiece().getLegalMoves().contains(new int[] {rowDifference, columnDifference});

Although it doesnt seem to work, return value is always false. Rest of the code seems relevant, forEach I'v put before prints "Ok move" when move is indeed ok. I could probably achieve what I want with some Iterator and for loops, but why do contains always returns false? Do I need to override equals() for class I want to check like that? Can't do that for an int[] tho, right? On the other hand, I could just use lambda and forEach like I did to print value. Still, I can't simply put return true inside that if statement...

Shubhendu Pramanik

Don't use Set<int[]>, instead use Set<Set<Integer>> because array doesn't implement equals and hashCode method and that's why contains won't work and that's why it returns false.

One option is iterate through the Set<int[]> and compare each element by Arrays.equals() method.

Or just use Set<Set> because Set implements equals and hashCode and you'll be able to use contains method

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at


Login to comment