开发者

Copying objects in java

开发者 https://www.devze.com 2023-04-11 22:49 出处:网络
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

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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消