gpt4 book ai didi

java - 定义多维数组列表的容量

转载 作者:太空宇宙 更新时间:2023-11-04 11:27:32 24 4
gpt4 key购买 nike

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

关于java - 定义多维数组列表的容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44181668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com