Converting an ArrayList into a 2D Array

前端 未结 8 2211
北海茫月
北海茫月 2020-12-04 01:55

In Java how do you convert a ArrayList into a two dimensional array Object[][]?

From comments: I will describe you the problem with more details: an XML file inclu

8条回答
  •  -上瘾入骨i
    2020-12-04 02:32

     ArrayList arrayList = new ArrayList();
        arrayList.add("element_1");
        arrayList.add("element_2");
        arrayList.add("element_3");
        arrayList.add("element_4");
        int k=0;
        int row = 2, col = 2;
        Object[][] objArray = new Object[row][col];
         for(int i = 0 ; i < row; i++) {
             for(int j = 0; j < col; j++) {
                     objArray[i][j] = arrayList.get(k);
                     k++;
                     if(k > arrayList.size()) {
                         break;
                     }
             }
         }
         for(int i = 0 ; i < row; i++) {
             for(int j = 0; j < col; j++) {
    
                 System.out.println("Row no "+i+" col no "+j+" "+objArray[i][j] );
             }
      }
     }
    

提交回复
热议问题