-3

-sがありArrayListます。ArrayList指定された行数と列数でフィールドを初期化するにはどうすればよいですか? 私はこれを試しました:

ArrayList<ArrayList<E>> field;

public Field(int rows, int cols) {
    field = new ArrayList<ArrayList<E>>(rows);
    for(ArrayList<E> t : field)
        t = new ArrayList<E>(cols);
}

しかし、うまくいきません。どうすればいいですか?

4

2 に答える 2

0

このことを考慮:

public class Field<E> {
    ArrayList<ArrayList<E>> field;

    public Field(int rows, int cols) {
        field = new ArrayList<ArrayList<E>>(rows);
        for (int i = 0; i < rows; i++) {
            ArrayList<E> row  = new ArrayList<E>(cols);
            for (int j = 0; j < cols; j++) {
                row.add(null);
            }
            field.add(row);
        }
    }

    public static void main(String[] args) {
        Field<String> field = new Field<String>(10, 10);
    }

}
于 2012-11-17T16:41:27.940 に答える
0

Listのサイズを初期化する必要はありません。

List を使用する主な理由は、そのサイズが変更される可能性があるためです。

リストを使用すると、次のことができます。

// declare and initialize List of Lists

List<List<Foo>> listOfFooLists = new ArrayList<List<Foo>>();

// create a List from some method

List<Foo> someFooList = createListOfFoos();

// add the List to the List of Lists

listOfFooLists.add(someFooList);

// get the first Foo from the first list of Foos

Foo f = listOfFooLists.get(0).get(0);
于 2012-11-17T08:45:36.440 に答える