gpt4 book ai didi

java - 深克隆数组对象时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:24:54 25 4
gpt4 key购买 nike

我相信我的代码是错误的,但有人可以纠正我的错误。我正在尝试深度克隆对象数组,但 A 类似乎不是深度复制,因为我遇到了麻烦。请一些人帮忙。我在复制数组 A 时遇到问题。

Class A implements Cloneable{
private int year;
private double data;

A(int year, double data)
{
setInt(year);
setDouble(data);
}
public void setInt(int year)
{
this.year = year;
}
public void setDouble(double data)
{
this.data = data;
}
public int getYear()
{
return year;
}
public double getData()
{
return data;
}
public Object clone()
{
A clonedA = new A(this.getYear(), this.getData());
return clonedA;
}}

class B implements Cloneable{
private A[] a;
private String name;
private int arraylength;
private int index;

public B(String name, int length)
{
this.name = name;
this.arraylength = length;
a = new A[array.length];
index = 0;
}

public void addToA(int year, double data)
{
a[index] = new A(year, data);
index++;
}
public String getName(){
return name; }
public int getLength(){
return array length;}

public void setName(String name)
{
this.name= name
}
public Object clone()
{
B clonedB = new B(this.getName(), this.getLength());

for(A clonedArray: a)
{
clonedB.addToA(clonedArray.getYear(), clonedArray.getData());
}
return clonedB;
}

最佳答案

B 类中的克隆方法似乎是错误的:我建议你做某事,比如

public Object clone()
{
B newB = new B(this.getName(), this.getLength());
for(int i =0;i<newB.a.length;i++)
{
newB.a[i] = a[i];
}
return newB;
}

您还可以尝试复制构造函数;

关于java - 深克隆数组对象时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26921899/

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