gpt4 book ai didi

java - 在java中复制对象

转载 作者:行者123 更新时间:2023-12-04 06:11:44 25 4
gpt4 key购买 nike

我想对一个对象执行深拷贝,是否clone函数工作到那个程度,还是我必须创建一个函数来物理复制它,并返回一个指向它的指针?也就是说,我想要

Board tempBoard = board.copy();

这会将板对象复制到临时板中,板对象保存在其中:
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;


}

最佳答案

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

关于java - 在java中复制对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7702469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com