繁体   English   中英

Java中使用Arraylist的动态2D数组

[英]dynamic 2d array in java using Arraylist

我在用arraylist创建动态2d数组时发现了一些问题,原始代码阅读起来很繁琐,所以我在这里给出了一个简单的代码,两种情况下的问题都是相同的:

import java.util.*;

class test{
 public static void main(String args[]){
    Integer test[]=new Integer[3];

    ArrayList<Integer[]> al=new ArrayList<Integer[]>();

    int i,t;

     test[0]=1;
     test[1]=2;
     test[2]=3;


     al.add(test);
     test[0]=4;
     test[1]=5;
     test[2]=6;

  al.add(test);

     test[0]=7;
     test[1]=8;
     test[2]=9;

  al.add(test);



     test[0]=10;
     test[1]=11;
     test[2]=12;
  al.add(test);



     Integer table[][]=new Integer[al.size()][];
     table=al.toArray(table);

     for(i=0;i<=al.size()-1;i++){

     for(t=0;t<3;t++){
       System.out.print(" "+i+" "+t+" ");
       System.out.print(" "+table[i][t]+" ");}
     System.out.println();
 }   

   }
}

输出:

 0 0  10  0 1  11  0 2  12
  1 0  10  1 1  11  1 2  12
 2 0  10  2 1  11  2 2  12
 3 0  10  3 1  11  3 2  12

预期输出为

 0 0   1  0 1  2  0 2  3
 1 0   4  1 1  5  1 2  6
 2 0   7  2 1  8  2 2  9
 3 0  10  3 1  11  3 2  12

我不明白为什么最后一个要素要覆盖所有其他要素。

每次添加新行时都要初始化一个新的Integer[]

也就是说,这样做:

Integer[] test = new Integer[3];
List<Integer[]> al = new ArrayList<Integer[]>();
int i,t;
test[0]=1;
test[1]=2;
test[2]=3;
al.add(test);
test = new Integer[3]; // Note this line
test[0]=4;
test[1]=5;
test[2]=6;
al.add(test);
test = new Integer[3]; // Note this line
test[0]=7;
test[1]=8;
test[2]=9;
al.add(test);
test = new Integer[3]; // Note this line
test[0]=10;
test[1]=11;
test[2]=12;
al.add(test);

或者更好的方法是这样做:

List<Integer[]> al = new ArrayList<Integer[]>();
al.add(new Integer[]{1, 2, 3});
al.add(new Integer[]{4, 5, 6});
al.add(new Integer[]{7, 8, 9});
al.add(new Integer[]{10, 11, 12});

数组是对象。 ArrayList.add(E)将对给定E对象的引用添加到列表中; 它不会复制对象本身。

因此,您应该执行以下操作:

al.add(test);
test = new int[3];

这将创建一个新的数组对象,因此将第二行数据写入一个单独的数组中。

暂无
暂无

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

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