2017-05-25 13 views
1

私はGridというクラスを作成しましたが、ネストされたArrayListの容量を定義することは苦労しています。多次元arraylistの容量を定義する

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

をしかし、これはエラーを与える:

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; 
    } 
} 

コードは次のようになります。これは私が現在持っているものです。誰もがこの問題を解決する方法を知っている、私は本当にそれを感謝します!前もって感謝します!

答えて

0

1つの初期化文では実行できません。ループが必要です。

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個以上の配列が割り当てられ、内容はコピーされます。

すべてのディメンションを調べ、オプションの初期容量セットで新しいリストを作成する必要があります。

関連する問題