Java动态二维数组 怎么动态定义

2025-03-22 02:30:30
推荐回答(4个)
回答1:

有两种实现方法:

  1. 可以用List数组来实现

  2. 可以用map来实现

方法一:用map来实现

比如要创建一个1行、3列的数组,实现方法如下:

public static void main(String[] args) throws CloneNotSupportedException {
   Map> myMap = create(1, 3);
}

public static Map> create(double row, double column) {
   Map> doubleMap = new HashMap>();

   for (double x = 0; x < row; x++) {
       for (double y = 0; y < column; y++) {
           doubleMap.put(x, new ArrayList());
       }
   }
   return doubleMap;
}

方法二:

可以用List数组来实现

 public static void main(String args[]) {

        //list 作为动态二维数组

        List> list = new ArrayList();

        List a1 = new ArrayList();

        List a2 = new ArrayList();

        List a3 = new ArrayList();

        list.add(a1);

        list.add(a2);

        list.add(a3);

        a1.add("string1 in a1");

        a1.add("string2 in a1");

        a2.add("string1 in a2");

        a3.add("string1 in a3");

        a3.add("string2 in a3");

        for (int i = 0; i < list.size(); ++i) {

            for (int j = 0; j < list.get(i).size(); ++j)

                System.out.println(list.get(i).get(j));

        }

    }

回答2:

int[][] num;
int[] a={1,23,4,5};//一个数组
int h=1;//多少行
num=new int[h][a.length];//这里用两个变量来就可以实现动态定义了.
for(int i=0;i{
for(int j=0;j {
num[i][j]=a[i];//这里实现动态赋值了
}
}

回答3:

回答4:

int[][] a=new int[10][10];

你想知道这个??