再一次,我正在寻找一种方法来绕过这个数组问题,如何?除了clone()
还有什么办法吗?我问是因为与克隆(),保护和实现的东西战斗对我不起作用......
//assuming you have proper class and constructor (point(int x, int y))
/*
point 7POINTSARRAY[]=new point[7];
for(int i=0;i<7;i++)
{
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
}
//This won't work, so...
*/
point B = new point(0,0); // You need this.
for(int i=0;i<7;i++){
7POINTSARRAY[i]=B; // And this.
//But I want to read and assign value only,
// not establish a reference, so it can work How?
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
System.out.println(7POINTSARRAY[i].x);
}
System.out.println(7POINTSARRAY[1].x);
虽然期望的输出是 A[1].x=1,但它已经被写了好几次,现在 A[1].x = 7。
如果您希望数组的每个元素都引用不同的对象,则需要为数组的每个元素创建一个新point
:
for(int i=0;i<7;i++)
{
point B = new point(0,0); // Put this *inside* the loop
7POINTSARRAY[i]=B; // Now B is a new instance of point
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
System.out.println(7POINTSARRAY[i].x);
}
System.out.println(7POINTSARRAY[1].x); // should now print 1
我没有更改您的代码格式,但改进这将使上述内容更清晰、更易于理解。
抱歉,Java 仅适用于复杂对象的引用。您应该正确使用和实施clone()
这不是问题。 clone()
定义明确的方法。
一级类的典型克隆如下所示
@Override
public Object clone() {
try {
A ans = (A) super.clone();
// do complex stuff
return ans;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
行
A ans = (A) super.clone();
执行默认克隆,其中包括克隆对象,但不包括其成员。您应该为成员级联克隆。由于clone()
是成员,因此它有权访问父级的受保护成员。
如果你的父母是Cloneable
你应该写
@Override
public Object clone() {
A ans = (A) super.clone();
// do complex stuff
return ans;
}
因为父级不能抛出异常。
例如,如果您有如下所示的点类
class point {
public point(double x, double y) { this.x = x; this.y = y; }
public double x;
public double y;
}
那么你应该通过以下方式修复它
class point implements Cloneable {
public point(double x, double y) { this.x = x; this.y = y; }
public double x;
public double y;
}
使其可克隆。
然后你就可以写了
point a = new point(1,2);
point b = (point) a.clone();
您将获得 2 份单独的副本。
问题出在行上
7POINTSARRAY[i]=B
这意味着 7POINTSARRAY 中的每个对象都引用(或点)同一个对象 B。
所以当你在循环内做
7POINTSARRAY[i].x=i;
7POINTSARRAY[i].y=i;
你实际上总是在改变 B。
您应该改为:
for(int i=0;i<7;i++){
7POINTSARRAY[i] = new point(i,i);
}