I tried to clone the object of Test2 using the "KUROONN" method. I expected the second line of the output to read [0,0], but the real result shows [33,4]. I have no idea why this happens, so can anyone explain this?
import java.util.ArrayList;
class Test {
public static ArrayList<Integer> T=new ArrayList<Integer>();
}
class Test2 {
int Test2Int;
ArrayList<Integer> Test2List;
public Test2(int K,ArrayList<Integer> A) {
this.Test2Int=K;
this.Test2List=A;
}
public Test2 KUROONN() { //broken clone
Test2 b=new Test2(0,Test.T);
b.Test2Int=this.Test2Int;
System.out.println(b.Test2List);
for(int i=0;i<this.Test2List.size();i++) {
b.Test2List.add(this.Test2List.get(i));
}
return b;
}
}
public class testtube001a {
public static void main (String args[]){
ArrayList<Integer> n =new ArrayList<Integer>();
n.add(33);
n.add(4);
ArrayList<Integer> m =new ArrayList<Integer>();
m.add(114);
m.add(514);
Test2 t2_1=new Test2(72,n);
Test2 t2_2=new Test2(1919,m);
t2_1.KUROONN();
t2_2.KUROONN();
}
}
The output of the program is:
[]
[33, 4]
You have declared the T field as:
The word
static
means the variable is shared between all instances. So when the codeis executed, it will create an instance of Test2 that references that shared variable. The first time it will be empty, and your print will result in
[]
. The second time it will reference the same list in which the first call added the values 33 and 4, hence it will print[33, 4]
. After that, the values 114 and 514 will also be added to the same list.