【发布时间】:2017-04-11 11:52:15
【问题描述】:
我正在处理对象中的一个函数,该函数将对象列表作为参数并将其内容克隆到自己的列表中。修改新的 List 应该不会影响传入的 List。我知道 List 会通过引用传递,但是列表中的对象是通过引用还是值传递? (对不起,如果这听起来很愚蠢)
我正在传递一个扩展 Piece 类的棋子列表(棋子、车等)。我正在考虑在 Piece 类中创建一个 clonePiece() 函数,但我不知道如何去做。这是我目前所拥有的:
public void copyPieces(List<Piece> whitePieces, List<Piece> blackPieces){
for (int i = 0; i < whitePieces.size(); i++){
this.whitePieces.add(whitePieces.get(i).clonePiece());
}
for (int i = 0; i < blackPieces.size(); i++){
this.whitePieces.add(blackPieces.get(i).clonePiece());
}
您将如何在一个抽象类中实现一个 clonePiece() 函数来创建其继承类的新实例?
编辑:
public abstract class Piece {
private int color;
private int x;
private int y;
public Piece (int color, int x, int y){
this.color = color;
this.y = y;
this.x = x;
}
public int getColor(){
return this.color;
}
public int getX(){
return this.x;
}
public int getY(){
return this.y;
}
public void move(int x, int y, Board board){
board.getGameTiles()[this.x][this.y].setToUnoccupied();
this.x = x;
this.y = y;
}
public abstract ArrayList<Move> getMoves(Board board);
public Piece clonePiece(){
return this;
}
}
public class Rook extends Piece{
int x, y, color;
private ArrayList<Move> moves;
public Rook(int color, int x, int y) {
super(color, x, y);
this.x = x;
this.y = y;
this.color = color;
moves = new ArrayList<>();
}
@Override
public ArrayList<Move> getMoves(Board board) {
//moves right
int a = 1;
while(UtilFunctions.isInBoundaries(x+a, y)){
if(!board.getGameTiles()[x+a][y].isTileOccupied()){
//add move type 0 for passive move
moves.add(new Move(x, y, x+a, y, 0));
}
else{
if(board.getGameTiles()[x+a][y].getPiece().getColor() != this.color){
//add move type 1 for attack move
moves.add(new Move(x, y, x+a, y, 1));
}
break;
}
a++;
}
//moves left
a = -1;
while(UtilFunctions.isInBoundaries(x+a, y)){
if(!board.getGameTiles()[x+a][y].isTileOccupied()){
//add move type 0 for passive move
moves.add(new Move(x, y, x+a, y, 0));
}
else{
if(board.getGameTiles()[x+a][y].getPiece().getColor() != this.color){
//add move type 1 for attack move
moves.add(new Move(x, y, x+a, y, 1));
}
break;
}
a++;
}
//moves up
a = 1;
while(UtilFunctions.isInBoundaries(x, y+a)){
if(!board.getGameTiles()[x][y+a].isTileOccupied()){
//add move type 0 for passive move
moves.add(new Move(x, y, x, y+a, 0));
}
else{
if(board.getGameTiles()[x][y+a].getPiece().getColor() != this.color){
//add move type 1 for attack move
moves.add(new Move(x, y, x, y+a, 1));
}
break;
}
a++;
}
//moves down
a = -1;
while(UtilFunctions.isInBoundaries(x, y+a)){
if(!board.getGameTiles()[x][y+a].isTileOccupied()){
//add move type 0 for passive move
moves.add(new Move(x, y, x, y+a, 0));
}
else{
if(board.getGameTiles()[x][y+a].getPiece().getColor() != this.color){
//add move type 1 for attack move
moves.add(new Move(x, y, x, y+a, 1));
}
break;
}
a++;
}
return moves;
}
}
【问题讨论】:
-
您也想自己克隆这些片段吗?是不可变的还是它们包含一些可变的状态?
-
是的,我想自己克隆这些片段并将它们放入新列表中。不确定可变性(我对编程很陌生),但 Pieces 只是扩展 Piece 类的类。 (即骑士、主教)
-
您能否发布
Piece类的代码以及它的后代之一?
标签: java oop inheritance deep-copy