I want to perform a deep copy on an object, does the clone
function work to that extent, or do I have to create a function to physically copy it, and return a pointer to it? That is, I want
Board tempBoard = board.copy();
This would copy the board object into the tempBoard, where the board object holds:
public interface Board {
Board copy();
}
public class BoardConcrete implements Board {
@override
public Board copy() {
//need to create a copy function here
}开发者_如何学Go
private boolean isOver = false;
private int turn;
private int[][] map;
public final int width, height;
}
The Cloneable
interface and the clone()
method are designed for making copies of objects. However, in order to do a deep copy, you'll have to implement clone()
yourself:
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;
}
}
精彩评论