2011-10-09 103 views
2

我想要在對象上執行深層複製,clone函數是否能夠在此範圍內工作,還是必須創建一個函數來物理複製它,並返回一個指向它的指針?也就是說,我想在java中複製對象

Board tempBoard = board.copy(); 

這將董事會對象複製到tempBoard,其中板對象包含:

public interface Board { 
    Board copy(); 
} 

public class BoardConcrete implements Board { 
    @override 
    public Board copy() { 
     //need to create a copy function here 
    } 

    private boolean isOver = false; 
    private int turn; 
    private int[][] map; 
    public final int width, height; 


} 
+0

http://stackoverflow.com/questions/2156120/java-recommended-solution-for-deep-cloning-copying -an實例/ 2156367#2156367 – Bozho

回答

3

Cloneable接口和clone()方法設計製作對象的副本。然而,爲了做一個深拷貝,你必須實現clone()自己:

public class Board { 
    private boolean isOver = false; 
    private int turn; 
    private int[][] map; 
    public final int width, height; 
    @Override 
    public Board clone() throws CloneNotSupportedException { 
     return new Board(isOver, turn, map.clone(), width, height); 
    } 
    private Board(boolean isOver, int turn, int[][] map, int width, int height) { 
     this.isOver = isOver; 
     this.turn = turn; 
     this.map = map; 
     this.width = width; 
     this.height = height; 
    } 
}