2011-10-09 136 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; 
    } 
}