始终包含 returns false
Contains always returns false
我正在编写国际象棋游戏,但在检查走法是否有效时遇到了问题。
长话短说,我得到了具有
的 Pawn(扩展 Piece)class
//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});
}
}
现在我得到另一个 class MoveValidator
来检查,显然,移动是否有效。
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});
}
虽然它似乎不起作用,但 return 值始终为 false。其余代码似乎是相关的,forEach
我在打印 "Ok move" 之前放了 move 确实可以。我可能可以用一些 Iterator
和 for loops
来实现我想要的,但为什么 contains
总是 return 为假?我是否需要为 class 覆盖 equals()
我想这样检查?不能为 int[]
做到这一点,对吧?
另一方面,我可以像打印值一样使用 lambda 和 forEach
。尽管如此,我还是不能简单地将 return true
放入 if statement
...
不要使用 Set<int[]>
,而是使用 Set<Set<Integer>>
因为数组没有实现 equals
和 hashCode
方法,这就是为什么 contains
不会'行不通,这就是为什么 returns false
.
一个选项是遍历 Set<int[]>
并通过 Arrays.equals()
方法比较每个元素。
或者只使用 Set<Set>
因为 Set
实现了 equals
和 hashCode
并且您将能够使用 contains
方法
我正在编写国际象棋游戏,但在检查走法是否有效时遇到了问题。
长话短说,我得到了具有
的 Pawn(扩展 Piece)class //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});
}
}
现在我得到另一个 class MoveValidator
来检查,显然,移动是否有效。
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});
}
虽然它似乎不起作用,但 return 值始终为 false。其余代码似乎是相关的,forEach
我在打印 "Ok move" 之前放了 move 确实可以。我可能可以用一些 Iterator
和 for loops
来实现我想要的,但为什么 contains
总是 return 为假?我是否需要为 class 覆盖 equals()
我想这样检查?不能为 int[]
做到这一点,对吧?
另一方面,我可以像打印值一样使用 lambda 和 forEach
。尽管如此,我还是不能简单地将 return true
放入 if statement
...
不要使用 Set<int[]>
,而是使用 Set<Set<Integer>>
因为数组没有实现 equals
和 hashCode
方法,这就是为什么 contains
不会'行不通,这就是为什么 returns false
.
一个选项是遍历 Set<int[]>
并通过 Arrays.equals()
方法比较每个元素。
或者只使用 Set<Set>
因为 Set
实现了 equals
和 hashCode
并且您将能够使用 contains
方法