簡體   English   中英

Java深克隆包含ArrayLists的對象

[英]Java Deepcloning an object that contains ArrayLists

我有一個叫做Board的類,其中包含以下內容

public class Board  {

protected Piece[][] GameBoard = new Piece[8][8];
ArrayList<Move> BlackBoardmoves = new ArrayList<Move>();
ArrayList <Move> WhiteBoardmoves = new ArrayList<Move>();

我想創建一個包含2個完全獨立的ArrayList的Board的全新對象,我已經讀了幾天的有關如何執行此操作的信息,並且我嘗試了各種方法,例如實現克隆或可序列化。 我已經知道克隆接口已損壞,並且使用可序列化的速度會慢得多,所以我決定編寫自己的復制方法

void copy(Board c)
{


for(int i =0; i<8; i++)  
{
for(int j=0; j<8; j++)
{
    this.GameBoard[i][j] = c.GameBoard[i][j];
}
}

for(int i=0 ;i<c.BlackBoardmoves.size(); i++)
{
this.BlackBoardmoves.add(c.BlackBoardmoves.get(i));
}

for(int i=0 ;i<c.WhiteBoardmoves.size(); i++)
{
this.WhiteBoardmoves.add(c.WhiteBoardmoves.get(i));
}
}

創建每個新對象時我目前正在做的事情是

Board obj2 = new Board();
obj2.copy(obj1);

這只是我項目的一小部分,所以我已經堅持了好幾天,實在花不起更多的時間來堅持下去。 非常感謝:)

首先,我建議使MovePiece對象不可變 使用這種方法,您只需要在這些對象上復制引用,而無需進行深度克隆。

private static <T> void copy2DArray(T[][] to, T[][] from) {
    for (int i = 0; i < to.length; i++)
        for (int j = 0; j < to[i].length; j++) {
            to[i][j] = from[i][j];
        }
}

void copy(Board c) {
    copy2DArray<Piece>(this.GameBoard, c.GameBoard);
    this.BlackBoardmoves = new ArrayList(c.BlackBoardmoves);
    this.WhiteBoardmoves = new ArrayList(c.WhiteBoardmoves);
}

您甚至想在這里做什么? 您希望副本有多深? 您只是將舊列表的內容復制到新列表中,這(對於適當的深層復制)可能不是您想要的。 您還以一種效率很低的方法來執行此操作,為什么不使用List類的“ addAll”方法呢?

但是您可能還想創建列表條目的副本,甚至可能要比它更深...無法確定,因為您在這里沒有說明您的要求。

在Board類內部,您可以放置​​將返回復制對象的方法,但是您需要適當的構造函數。 您還必須在Piece類內部添加相同的方法,以從數組中深度復制每個對象。

Board(Object[][] GameBoard, ArrayList<Object> BlackBoardObjects, ArrayList <Object> WhiteBoardObjects){
    this.GameBoard = GameBoard;
    this.BlackBoardObjects = BlackBoardObjects;
    this.WhiteBoardObjects = WhiteBoardObjects;
}

public Board getCopy(){
    for(int i = 0; i < GameBoard.length; i++){
        for(int j = 0; j < GameBoard[0].length; j++){
            GameBoardCopy[i][j] = GameBoard[i][j].getCopy();
        }
    }
    ArrayList<Move> BlackBoardObjectsCopy = new ArrayList<Move>(BlackBoardObjects);
    ArrayList <Move> WhiteBoardObjectsCopy = new ArrayList<Move>(WhiteBoardObjects);
    return new Board(GameBoard, BlackBoardObjectsCopy, WhiteBoardObjectsCopy);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM