定义多维数组列表的容量



我创建了一个名为Grid的类,我正在努力定义嵌套ArrayList的容量。这是我目前拥有的:

public class Grid extends GameObject {
   private int cols;
   private int rows;
   private int colWidth;
   private int rowHeight;
   private ArrayList<ArrayList<GameObject>> contents;
   public Grid(int x, int y, int cols, int rows, int colWidth, int rowHeight, ID id) {
       super();
       this.x = x;
       this.y = y;
       this.cols = cols;
       this.rows = rows;
       this.colWidth = colWidth;
       this.rowHeight = rowHeight;
       //Here I want to define the contents
       this.width = colWidth * cols;
       this.height = rowHeight * rows;
       this.id = id;
   }
 }

代码应如下所示:

this.contents = new ArrayList<ArrayList<GameObject>(cols)>(rows);

但这给出了一个错误。有谁知道如何解决这个问题,我将不胜感激!提前感谢!

不能使用单个初始化语句来执行此操作。你需要一个循环。

this.contents = new ArrayList<ArrayList<GameObject>>(rows); // this creates an empty 
                                                            // ArrayList
for (int i = 0; i < rows; i++) { // this populates the ArrayList with rows empty ArrayLists
    this.contents.add(new ArrayList<GameObject>(cols));
    // and possibly add another loop to populate the inner array lists
}

在创建列表时定义大小。

contents = new ArrayList<>(x);
contents.add(new ArraysList<GameObject>(y));

您根本无法做到这一点,因为从应用程序的角度来看,它是单一的尺寸列表。此外,new ArrayList<?>(N)没有定义列表的最大容量(像new GameObject[N]那样(,但它定义了它的初始容量。将 N 个元素添加到该列表后,您仍然可以添加更多元素,因为内部将分配另一个数组,这次比 N 大,并且内容将被复制。

您需要查看每个维度,并创建具有可选初始容量集的新列表。