I have this:
import java.util.ArrayList;
public class MyClass {
ArrayList list = new ArrayList();
public MyClass(){
}
public MyClass(MyClass aClass){
this.list = aClass.getList();
}
public void add(int number){
list.add(number);
}
public void set(int number){
list.set(0, number);
}
public int get(){
return (Integer)list.get(0);
}
public ArrayList getList(){
return list;
}
}
MyClass aName = new MyClass();
aName.add(5);
System.out.println("aName: "+aName.get());
MyClass aName2 = new MyClass(aName);
System.out.println("aName2: "+aName2.get());
aName2.set(1);
System.out.println("aName2: "+aName2.get());
System.out.println("aName: "+aName.get());
This will print:
aName: 5
aName2: 5
aName2: 1
aName: 1
I don’t want my second object changing the values in my first object.
Is there any way to stop this happening but still be able to copy properties from another object?
Then don’t pass the List from the original object to the new object, in
It makes both object have a reference to the same list (there is only one list shared between both objects).
You should do