简体   繁体   English

从ArrayList创建二维数组<Integer>

[英]Create a 2d array from an ArrayList<Integer>

I have an ArrayList and I want to create a method that will turn it into a 2d array, int[][]. 我有一个ArrayList,我想创建一个将其转换为2d数组int [] []的方法。 This new 2d array will represent a matrix and it has to be square, so for example if I use [8, 2, 3, 0] the ressult will be {8,2} {3,0} 这个新的2d数组将表示一个矩阵,并且必须为正方形,因此,例如,如果我使用[8,2,3,0],则结果为{8,2} {3,0}

public static int[][] convertIntegers(ArrayList<Integer> integers){
        int m = (int) Math.sqrt(integers.size());
        int[][] ret = new int[m][m];

        int cont = 0;

        for(int i=0; i<m+1 ; i++)
       {
           for(int j=0; j<m; j++)
           {
               cont = cont + 1;
               ret[i][j] = integers.get(cont);
               ;
           }
       }
       return ret;}

Your implementation is almost ok, except for some off-by-one errors: 您的实现几乎可以,除了一些一次性错误:

  • You need to increment cont after the integers.get call, not before. 您需要在integers.get调用之后而不是之前增加cont If you increment before, then the first element of the list will be skipped. 如果之前增加,则列表的第一个元素将被跳过。 An easy way to fix that is to move the incrementing inside the inner loop, counting it together with j . 一种简单的解决方法是在内部循环内移动增量,并将其与j一起计数。
  • The outer loop should go until i < m instead of i < m + 1 外循环应持续到i < m而不是i < m + 1

With the errors fixed: 修复错误:

for (int i = 0, cont = 0; i < m; i++) {
  for (int j = 0; j < m; j++, cont++) {
    ret[i][j] = integers.get(cont);
  }
}

Btw, another way is without using cont at all, calculating the correct position using i , j and m : 顺便说一句,另一种方法是根本不使用cont ,而是使用ijm计算正确的位置:

for (int i = 0; i < m; i++) {
  for (int j = 0; j < m; j++) {
    ret[i][j] = integers.get(i * m + j);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM