gator
gator

Reputation: 3523

Convert arraylist of arraylists to array?

I have something like the below:

ArrayList<Integer>[] aL = new ArrayList[25];
for (int i = 0; i < aL.length; i++) {
    aL[i] = new ArrayList<Integer>();
}

After some logic, I come upon a structure like below:

aL[0] = {492,19,183,193};
aL[1] = {13};
aL[2] = {19,56};
aL[3] = {};
aL[4] = {1};
...

I want to concatenate aL into a new continuous array. The end result for the above example would be newArray = {492,19,183,193,13,19,56,1,...}. To note is that I know exactly how many integers there should be in total. I've attempted the below:

newArray = new int[100]; //recall the number of ints is defined, ex. 100
int a = 0;
for (int i = 0; i < aL.length; i++) { 
    for (int k = 0; k < aL[i].size(); k++) {
        newArray[a] = aL[i].remove(0);
        a++;
    }
}

Upon printing the array, some values are missing. I'm checking how many times the nested loop iterates, and sometimes when aL[i].size() is 5 for example, it might only iterate 4 times.

Upvotes: 0

Views: 90

Answers (2)

NiziL
NiziL

Reputation: 5140

for( int k = 0; k < aL[i].size() ; k++ ) {
  newArray[a++] = aL[i].remove(0);
}

Let's see what happens here !
You start with a list of 5 elements:
- k == 0 and aL[i].size() == 5
0 < 5 so go in the for loop, remove the first element of the list and increment k
- k == 1 and aL[i].size() == 4
1 < 4, same
- k == 2 and aL[i].size() == 3
2 < 3, same
- k == 3 and aL[i].size() == 2
3 < 2 is false, so you stop

As you can see, there is only 3 elements removed from the list :)

There are a lot of solution, for example:

for( int k = 0; k < aL[i].size() ; k++ ) {
  newArray[a++] = aL[i].get(k);
}
aL[i].clear()

Upvotes: 1

Eran
Eran

Reputation: 394006

If you must remove elements from the ArrayLists while iterating over them, you should use a while loop :

while (aL[i].size() > 0) {
    newArray[a] = aL[i].remove(0);
    a++;
}

However, as commented by Smutja, it's preferable to iterate over the ArrayLists without modifying them.

newArray = new int[100]; //recall the number of ints is defined, ex. 100
int a = 0;
for (int i = 0; i < aL.length; i++) { 
    for (int value : aL[i]) {
        newArray[a] = value;
        a++;
    }
}

Upvotes: 1

Related Questions