-3

I want to convert ArrayList to Array 2-Dimension

I have the code below:

ArrayList<String> arrayList=new ArrayList();
arrayList.add("A")
arrayList.add("B")
arrayList.add("C")
arrayList.add("D")
arrayList.add("E")
arrayList.add("F")

int nSize=0,n3item=0, remain=0;
nSize=arrayList.size();
n3item=nSize/3;
remain=nSize%3;
String[][] array[n3item][3]

I want to convert ArrayList to array for example
array[0][1]="A"
array[0][2]="B"
array[0][3]="C"
array[1][1]="D"
array[1][2]="E"
array[1][3]="F"

Now I haven't a solution to do this. In case of remain is not 0. How to give a solution to this problem I need your help.

Thanks.

Herry
  • 7,037
  • 7
  • 50
  • 80
  • 2
    Possible duplicate of [How to convert a 1d array to 2d array?](https://stackoverflow.com/questions/5134555/how-to-convert-a-1d-array-to-2d-array) – Shashwat Mar 29 '18 at 04:18

2 Answers2

1

You can use a simple nested for-loop to achieve this.

int numCol = 3;
int numRow = (int) Math.ceil(arrayList.size() / ((double) numCol));
String[][] array = new String[numRow][numCol];

int i, j;
for (i = 0; i < numRow; i++) {
    for (j = 0; j < 3 && (i * numCol + j) < arrayList.size(); j++) {
        array[i][j] = arrayList.get((i * numCol) + j);
    }
}

numRow is found by taking the ceil of number of elements in the list divided by num of desired columns. eg - when arraylist has 7 elements, numRow will be ceil(7/3.0) = 3.

The main trick here is in the inner for-loop condition (i * numCol + j) < arrayList.size(). It enables us to terminate the loop for the condition remain != 0 you mentioned.

Thiyagu
  • 17,362
  • 5
  • 42
  • 79
0

Try to think, how you can fill the 2D array with arraylist values. You need to use a nested loop for assigning the values into the 2D array. Outer loop will iterate over the rows and inner loop will fill the values into each 1D array.

int index = 0;
for(int i = 0; i < n3item; i++) {
    for(int j = 0; j < 3; j++) {
        array[i][j] = arrayList.get(index);
        index++;
    }
}
Shahid
  • 2,288
  • 1
  • 14
  • 24