Writing multiple Arrays into an Arraylist

boge_ :

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]]
Scary Wombat :

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);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=217122&siteId=1