在java中克隆数组
这是克隆阵列的正确方法吗?我想创建AccountWithInterface的深度副本,其中定义了克隆方法。我已经读过深拷贝和浅拷贝的区别,所以请不要链接来解释它们的区别。这正是我目前遇到的语法问题在java中克隆数组,java,deep-copy,shallow-copy,arrays,Java,Deep Copy,Shallow Copy,Arrays,这是克隆阵列的正确方法吗?我想创建AccountWithInterface的深度副本,其中定义了克隆方法。我已经读过深拷贝和浅拷贝的区别,所以请不要链接来解释它们的区别。这正是我目前遇到的语法问题 // create object AccountWithInterface accountTemplate = new AccountWithInterface(name, balance, id, rate); // declare object AccountW
// create object
AccountWithInterface accountTemplate = new AccountWithInterface(name, balance, id, rate);
// declare object
AccountWithInterface[] accountArray = new AccountWithInterface[3];
// create each accountArray object
for(int i = 0; i < accountArray.length; i++) {
accountArray[i] = new AccountWithInterface();
// copy each element (object)
accountArray[i] = (AccountWithInterface)accountArray[i].clone();
}
public Object clone() throws CloneNotSupportedException {
AccountWithInterface acctClone = (AccountWithInterface)super.clone();
return acctClone;
}
//创建对象
AccountWithInterface accountTemplate=新的AccountWithInterface(名称、余额、id、费率);
//声明对象
AccountWithInterface[]accountArray=新AccountWithInterface[3];
//创建每个accountArray对象
for(int i=0;i
Rly?如果你问了一个关于语法的问题,而不是100个不同站点的链接,那么就投反对票吧?不要乱搞clone()
和Clonable()
;它坏得可怕,很少做你需要或期望的事情。您的逻辑很好,您只需要为AccountWithInterface
创建一个“复制构造函数”,它接受一个现有的AccountWithInterface
实例,在实例化新的构造函数的过程中,将现有构造函数的所有内容深度复制到新的构造函数中。不知道你的意思,但我现在将查看如何创建复制构造函数,并在AccountWithInterface
中定义一个构造函数,签名为:public AccountWithInterface(AccountWithInterface existing)
。在sonstructor中,您将旧结构的内容复制到正在构建的新结构中;那是一份深度拷贝。请注意,您还需要深度复制AccountWithInterface
中包含的任何可变对象。