S_I_M_O_N
S_I_M_O_N

Reputation: 63

Dynamically allocated array of arrays in java

I have a problem with array of arrays object. I tried the default Java array like this:

String[][] array = new String[5][5];

And it worked. But now I'm facing for another problem. I don't know the sizes of the array so I need a dynamically allocated array of arrays. I tried this:

ArrayList<String> array = new ArrayList<>();
ArrayList<ArrayList<String>> arrayOfArrays = new ArrayList<>();

array.add("1");
array.add("2");
array.add("3");
arrayOfArrays.add(array);
System.out.println(arrayOfArrays);
array.clear();
array.add("4");
array.add("5");
array.add("6");
arrayOfArrays.add(array);
System.out.println(arrayOfArrays);

And it prints:

[[1, 2, 3]]
[[4, 5, 6], [4, 5, 6]]

And I don't need to rewrite it. It should looks like this:

[[1, 2, 3]]
[[1, 2, 3], [4, 5, 6]]

I'm facing for this problem very long time and I tried a lot of workarounds but I need some clever solution. Also I will appreciate any help.

And I have a second question. How to add it in cycle? Because it has the same output as in the first case. For example:

for (int i = 0; i < array.size() - 1; i++) {
    arrayOfArrays.add(swap(array, i, i+1));       
}

Upvotes: 1

Views: 140

Answers (2)

Duong Nguyen
Duong Nguyen

Reputation: 850

You should be aware that you're just using the same array object, and add it to the arrayOfArrays twice, that why it prints out the same thing twice.

What you need is actually this:

    ArrayList<ArrayList<String>> arrayOfArrays = new ArrayList<>();

    ArrayList<String> array1 = new ArrayList<>();
    array1.add("1");
    array1.add("2");
    array1.add("3");
    arrayOfArrays.add(array1);
    System.out.println(arrayOfArrays);

    ArrayList<String> array2= new ArrayList<>();
    array2.add("4");
    array2.add("5");
    array2.add("6");
    arrayOfArrays.add(array2);
    System.out.println(arrayOfArrays);

Upvotes: 1

Eran
Eran

Reputation: 393771

You are adding the same ArrayList instance twice to the outer List.

You need to create two distinct ArrayList instances to add to your arrayOfArrays.

Replace

array.clear();

with

array = new ArrayList<>();

Upvotes: 2

Related Questions