# Algorithm to convert 1-d array to 2-d array

Patrick Noah
Greenhorn
Posts: 28
Suppose I have a 6 item array I want to convert to a 2*3 array. So imagine [1,2,3,4,5,6] to
1 2 3
4 5 6

I want to do something like:
for(int row=0; row < 2; row++)
for(int col=0; col < 3; col++)
2darray[row][col] = pop 1-d array from first element

but java arrayList doesn't support this "pop array from first element" like perl does. How do I go upon doing this? Thanks.

John Jai
Rancher
Posts: 1776
ArrayList has a remove() method. If you use like remove(0), it will return the leftmost element and hence you get 1,2,3,4,5,6 popped out of the List in order (if you have added in that order).

You can also store the numbers [1,2,3,4,5,6] in an int array instead of an ArrayList.

Campbell Ritchie
Sheriff
Posts: 49364
62
There is no such thing as a 2-D array. What you are showing is an array of arrays, which is actually better than a 2-D array.
What are you trying to change? You said “array” in the thread title and “ArrayList” later on. You cannot get an array out of an element.
What you are trying to do is count the first 3 elements, put them into an array, then repeat. It is a simple enough operation if you remember what the 5 arithmetical operators are.

Campbell Ritchie
Sheriff
Posts: 49364
62
Don’t use literals in for loops if you can possibly avoid it. There is a .length field implicitly available in every array, which you can use in the for loop.