简体   繁体   English

将ArrayList转换为2D数组

[英]Converting ArrayList to 2D array

After figuring out a way pof create of list of random numbers from 1 to 16, how can I display this list in matrix form. 确定了从1到16的随机数列表的pof创建方式后,如何以矩阵形式显示此列表。

 public static void main(String... args) throws Exception {

 List<Integer> list = new ArrayList<Integer>();
 for (int i = 1; i < 17; i++) {
    list.add(i);
}
System.out.println(list); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Collections.shuffle(list);
System.out.println(list); //[11, 5, 10, 9, 7, 0, 6, 1, 3, 14, 2, 4, 15, 13, 12, 8]

int[][] a2 = new int[4][4];
for (int i = 0; i < 4; i++) {
    for (int j = 0;  j< 4; j++) {


        a2[i][j] = list.get(i*4 + j);
      //  System.out.println(Arrays.deepToString(a2)); //[[11, 5, 10, 9], [7, 0, 6, 1],     [3, 14, 2, 4], [15, 13, 12, 8]]
    }
   System.out.println(Arrays.deepToString(a2)); //[[11, 5, 10, 9], [7, 0, 6, 1], [3,     14, 2, 4], [15, 13, 12, 8]]
}
//System.out.println(Arrays.deepToString(a2)); //[[11, 5, 10, 9], [7, 0, 6, 1], [3, 14                  2, 4], [15, 13, 12, 8]]
}

Like this : 像这样 :
3, 4, 5, 8, 3、4、5、8
2, 6, 7, 9, 2、6、7、9
11, 1, 15, 13, 11、1、15、13
10, 12, 14, 0 10、12、14、0

I put a zero at the end because I want it to present a void that can be moved by the user, using boolean operators. 我在结尾处加一个零,因为我希望它提供一个可以由用户使用布尔运算符移动的空白。

Your two for-loops breaks the list into a 2D array just fine. 您的两个for循环将列表分成2D数组就好了。

To print the a2 matrix you could for instance do the following: 打印 a2矩阵,您可以例如执行以下操作:

for (int[] row : a2) {
    System.out.print("[");
    for (int i : row)
        System.out.printf("%4d", i);
    System.out.println("]");
}

Result: 结果:

[   6  11   3   7]
[   4  14   5   9]
[   2  13  16  10]
[   8   1  12  15]

Something like this: 像这样:

int index = 1;
for(Integer i : list) {
  System.out.print(i);
  if (index % 4 == 0)
    System.out.println();
  index++;
}

If you need ArrayList and Random, then you can use the following: 如果需要ArrayList和Random,则可以使用以下命令:

Random random = new Random();
ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>();
for(int i=0;i<4;i++) {
    ArrayList<Integer> array = new ArrayList<Integer>();
    for (int j=0;j<4;j++) {
        array.add(random.nextInt(16)+1);
    }
    matrix.add(array);
}

And then you can simply iterate over the matrix and print each array. 然后,您可以简单地遍历矩阵并打印每个数组。

for(ArrayList<Integer> array: matrix) {
    System.out.println(array);
}

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

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