Creating arraylist of arrays

后端 未结 5 1912
误落风尘
误落风尘 2021-01-13 03:34

I\'m trying to create an array list of string arrays. When I am done, I want the array list to look like this:

[0,0], [0,1], [1,0], [1,1,]

5条回答
  •  囚心锁ツ
    2021-01-13 04:13

    The problem is that you are adding the same object to each index of your ArrayList. Every time you modify it, you are modifying the same object. To solve the problem, you have to pass references to different objects.

    String[] t2 = new String[2]; 
    
    ArrayList list2 = new ArrayList();
    
    t2[0]="0";
    t2[1]="0";
    list2.add(t2); 
    
    t2 = new String[2]; // create a new array
    t2[0]="0";
    t2[1]="1";
    list2.add(t2);
    
    t2 = new String[2];
    t2[0]="1";
    t2[1]="0";
    list2.add(t2);
    
    t2 = new String[2];
    t2[0]="1";
    t2[1]="1";
    list2.add(t2);
    

提交回复
热议问题