我正在处理一个对象中的函数,该对象将对象列表作为参数并将其内容克隆到其自己的列表中。修改新列表不应该影响传入的列表。我知道列表将通过引用传递,但列表中的对象是否可以通过引用或值传递? (对不起,如果这听起来很愚蠢)在Java中克隆列表
我正在传递一个片断(典当,白嘴鸦等)的列表,它扩展了一个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'类的代码和它的一个后代呢? –