In Java, I’m attempting to build a copy constructor. I’m having trouble with the class’s non-primitive type fields. It is sharing the members while producing a new copy. As an example,
public class Bad implements Cloneable {
private ArrayList<Integer> a;
private Object c;
public static void main(String[] args) {
Bad b1 = new Bad();
b1.a.add(10);
System.out.println(b1.a);
Bad b2 = b1.clone();
b2.a.add(12);
System.out.println(b1.a);
}
Bad() {
a = new ArrayList<>();
c = null;
}
Bad(Bad b) {
a = b.a;
c = b.c;
}
public Bad clone() {
return new Bad(this);
}
}
As a result of this,
[10]
[10, 12]
This is not something I want to happen. Consider the following example given in here. My original issue has even more user-defined fields.
Or are there libraries that will perform the work for me? Thank you ahead of time.