二维ArrayList

我知道我可以通过在它旁边添加另一个[]来为数组添加维度。 但是我可以在java.util.ArrayList中拥有多个Dimension吗? 我怎么能做到这一点?

是的,这是可能的。 只需让ArrayList的元素也是ArrayLists

 ArrayList> twoDArrayList = new ArrayList>(); 

这不仅适用于ArrayLists ,也适用于其他集合类型。

 List> twoDArrayList = new ArrayList>(); 

@ rgettman的回答完成了工作,但有几点需要注意:

警告1:尺寸

在最常见的用例中,数组的维度是预定义的,例如:

 int[][] array = new int[5][6]; 

在这种情况下,数组将是定义的维度的“矩形”forms:

  0 1 2 3 4 5 0 [][][][][][] 1 [][][][][][] 2 [][][][][][] 3 [][][][][][] 4 [][][][][][] 

正如下面评论中的另一位成员所建议的那样,还有更多内容。 “二维数组”仅仅是其他数组的数组,上面的代码行是简写的:

 int[][] array = new int[5][]; array[0] = new int[6]; array[1] = new int[6]; array[2] = new int[6]; array[3] = new int[6]; array[4] = new int[6]; 

或者,子数组可以用不同的大小进行实例化,在这种情况下,“数据形状”将不再是矩形:

 int[][] array = new int[5][]; array[0] = new int[2]; array[1] = new int[4]; array[2] = new int[1]; array[3] = new int[6]; array[4] = new int[3]; 0 1 2 3 4 5 0 [][] 1 [][][][] 2 [] 3 [][][][][][] 4 [][][] 

使用ArrayList>方法将产生“列表列表”,其中所涉及的所有列表的长度将由于执行的操作而增长。

没有预先定义尺寸的简写。 必须将子列表插入主列表,然后必须将数据元素插入子列表中。 因此,数据的形状类似于第二个示例:

 0 [][] <- list with 2 elements 1 [][][][] <- list with 4 elements 2 [] ...and so on 3 [][][][][][] 4 [][][] 

警告2:数据的默认值

数组允许使用原始数据类型(例如“int”),以及它们的盒装对应物(例如“Integer”)。 当涉及到元素的默认值时,它们的行为会有所不同。

 int[][] array1 = new int[5][6]; // all elements will default to 0 Integer[][] array2 = new Integer[5][6]; // all elements will default to null 

列表(与所有其他集合一样)仅允许使用盒装类型。 因此,虽然可以预先定义列表的长度,但其元素的默认值将始终为null。

 List = new ArrayList(10); // all elements will default to null 

是的你可以! 在常规数组中,当您添加第二对大括号时,您将创建一个存储类型为Array的对象的普通数组。 你可以在这里做同样的事情,使ArrayList保存类型为ArrayList: ArrayList> list = new ArrayList>();