将内存分配给类的对象

Nee*_*raj 1 java

我有一个包含类对象的列表

List a[10];

class Hello extends abc implement xyz
{ 
String mesg1;
String mesg2;
Object c;
Goodbye d;
// also their getter setters
}
Run Code Online (Sandbox Code Playgroud)

a [5]包含Hello类的对象

我必须在位置1复制对象实例然后在mesg1和mesg2中做一些更改并在最后将它插入到同一列表中.我试图这样做,但是因为我们知道它只存储在那里的引用所以我结束也改变了位置1的mesg1和mesg2.

有什么建议 ?我尝试使用clone()但不能对此类或Hello类进行更改.

T.J*_*der 7

您必须提供自己的clone或复制构造函数作为Hello类的一部分.

例如(clone):

public Hello clone() {
    Hello h;

    h = new Hello();
    h.mesg1 = this.mesg1;
    h.mesg2 = this.mesg2;
    h.c = this.c; // Or a deep copy if appropriate
    h.d = this.d; // Or a deep copy if appropriate

    return h;
}
Run Code Online (Sandbox Code Playgroud)

或(复制构造函数):

public Hello(Hello original) {
    this.mesg1 = original.mesg1;
    this.mesg2 = original.mesg2;
    this.c = original.c; // Or a deep copy if appropriate
    this.d = original.d; // Or a deep copy if appropriate
}
Run Code Online (Sandbox Code Playgroud)

然后使用它

a[5] = new Hello();
// set its members
a[1] = a[5].clone(); // or = new Hello(a[5]);
// set its members
Run Code Online (Sandbox Code Playgroud)