Creating arraylist of arrays

后端 未结 5 1918
误落风尘
误落风尘 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<String[]> list2 = new ArrayList<String[]>();
    
    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);
    
    0 讨论(0)
  • 2021-01-13 04:13

    You are adding the same array t2 over and over. You need to add distinct arrays.

    ArrayList<String[]> list2 = new ArrayList<String[]>();
    
    list2.add(new String[] {"0", "0"});
    list2.add(new String[] {"0", "1"});
    list2.add(new String[] {"1", "0"});
    list2.add(new String[] {"1", "1"});
    

    As an aside: you can use Arrays.toString(tt) inside the loop to format each String[] the way you are doing.

    0 讨论(0)
  • 2021-01-13 04:24

    You are only creating one array, and putting its reference repeatedly into the ArrayList.

    Instead, you can create a new array for each element in the List:

     ArrayList<String[]> list2 = new ArrayList<String[]>();
    
     String[] t2; 
    
     t2 = new String[2]; 
     t2[0]="0";
     t2[1]="0";
     list2.add(t2);
    
     t2 = new String[2]; 
     t2[0]="0";
     t2[1]="1";
     list2.add(t2);
    
     t2 = new String[2]; 
     t2[0]="1";
     t2[1]="0";
    
     t2 = new String[2]; 
     list2.add(t2);
     t2[0]="1";
     t2[1]="1";
     list2.add(t2);
    
    0 讨论(0)
  • 2021-01-13 04:26

    You have just one item (t2) and each time you add it to the ArrayList . actually the reference of t2 is going to be saved in ArrayList so when you change the t2 value all of references in the ArrayList take effect.

    0 讨论(0)
  • 2021-01-13 04:32

    This is because you're adding t2 to all of the entries. Each time you overwrite t2 you're changing all the values. This is because t2 isn't being passed by value, it is being passed by reference and saved by reference.

    0 讨论(0)
提交回复
热议问题