0

Whenever I've been trying to write an array to any type of a list I get the same output and I don't seem to understand where I'm doing wrong. For some reason, every array instance in the Arraylist equals to last cycle of the for loop.

Here's the example code

public class Test {
    public static void main(String[] args) {
        ArrayList<String[]> al = new ArrayList<>();
        String[] a = new String[2];

        for (int i = 0; i < 4; i++) {
            a[0] = "boo";
            a[1] = String.valueOf(i);
            al.add(a);
        }
    }
}

With the output

[[boo, 3], [boo, 3], [boo, 3], [boo, 3]]
boge_
  • 3
  • 1

2 Answers2

0

Move your array into your for loop, otherwise you are just using the same variable

for (int i = 0; i < 4; i++) {
    String[] a = new String[2];
    a[0] = "boo";
    a[1] = String.valueOf(i);
    al.add(a);
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

Here is the problem. You need to create the array inside the loop. Otherwise you are overwriting the same one.

public class Test {
    public static void main(String[] args) {
        ArrayList<String[]> al = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            String[] a = new String[2];
            a[0] = "boo";
            a[1] = String.valueOf(i);
            al.add(a);
        }
    }
}
WJS
  • 36,363
  • 4
  • 24
  • 39