-1

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]
Per Huss
  • 4,755
  • 12
  • 29
  • Why would you expect the output [0,0]? You never set that as far as I see. Besides please don´t use Test, Test2 as class names and then name the variables Test2Int. Even though the code is relativly simple it makes it pretty hard to understand. And is the ArrayList in class Test static for a specific reason? Because if not I would remove that thing first. – Alexander Heim Sep 14 '17 at 07:40
  • Sorry for my mistake. I meant I expected []. And this code was supposed to be just a debugging test for a bigger code I'm making, so I just used tests for names. Very Sorry. – Nayuta Ito Sep 14 '17 at 08:44

1 Answers1

0

You have declared the T field as:

public static ArrayList<Integer> T=new ArrayList<Integer>(); 

The word static means the variable is shared between all instances. So when the code

Test2 b=new Test2(0,Test.T);

is 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.

Per Huss
  • 4,755
  • 12
  • 29