2017-05-25 31 views
1

我创建了一个名为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); 

但是,这给出了一个错误。有谁知道如何解决这个问题,我真的很感激它!提前致谢!

回答

0

你不能用一个初始化语句来做到这一点。你需要一个循环。

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 
} 
+0

我有点希望这是可能的,但这将不得不做。谢谢! – Trashtalk

0

定义创建列表时的大小。

contents = new ArrayList<>(x); 

contents.add(new ArraysList<GameObject>(y)); 
0

从应用程序的角度来看,您根本无法做到这一点,它是单维列表。 new ArrayList<?>(N)也没有定义列表的最大容量(如new GameObject[N]会),但它定义了它的初始容量。将N个元素添加到该列表后,您仍然可以添加更多的内部其他数组将被分配,此时大于N,内容将被复制。

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