本文介绍了如何在java中创建动态二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态创建一个二维数组。

I want to create a two dimensional array dynamically.

我知道列数。但行数正在动态更改。我尝试了数组列表,但它只将值存储在单维度中。我该怎么办?

I know the number of columns. But the number of rows are being changed dynamically. I tried the array list, but it stores the value in single dimension only. What can I do?

推荐答案

由于列数是一个常数,你可以得到一个列表 int []

Since the number of columns is a constant, you can just have an List of int[].

    import java.util.*;
    //...

    List<int[]> rowList = new ArrayList<int[]>();

    rowList.add(new int[] { 1, 2, 3 });
    rowList.add(new int[] { 4, 5, 6 });
    rowList.add(new int[] { 7, 8 });

    for (int[] row : rowList) {
        System.out.println("Row = " + Arrays.toString(row));
    } // prints:
      // Row = [1, 2, 3]
      // Row = [4, 5, 6]
      // Row = [7, 8]

    System.out.println(rowList.get(1)[1]); // prints "5"

由于它以列表,行数可以动态增长和缩小。每行都有一个 int [] 支持,这是静态的,但你说列数是固定的,所以这不是问题。

Since it's backed by a List, the number of rows can grow and shrink dynamically. Each row is backed by an int[], which is static, but you said that the number of columns is fixed, so this is not a problem.

这篇关于如何在java中创建动态二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:20