我正在尝试创建一个创建定义的2d arraylist的类,并且具有添加对象和删除给定x / y的对象的方法。将会有另一个类添加和删除对象,并检查空间是否打开。我找到了一个例子,但它似乎对我的需求来说太复杂了,我不想复制他们的工作,因为我想学点东西。我没有使用ArrayList的经验,但我已经阅读了Java Docs并理解了它的要点。这是我正在查看的示例的链接(这是第一篇文章):http://www.javaprogrammingforums.com/java-programming-tutorials/696-multi-dimension-arraylist-example.html
我对2D数组列表的理解是它只是一个引用另一个ArrayList的ArrayList。就像我之前说过的,我只想要一个处理所有杂乱内容并添加和删除对象的类。这就是我所拥有的;我觉得这是完全错误的,因为当我尝试将列表添加到另一个列表时,我得到一个错误,说“不能在原语类型int上调用get(int)”。如果有人能帮我走上正轨,我会非常感激。这是我到目前为止所做的:
public class BoardMap {
private int numOfCols;
private int numOfRows;`
private ArrayList<GameObject> cols = new ArrayList<GameObject>(numOfCols);
private ArrayList<GameObject> rows = new ArrayList<GameObject>(numOfRows);
@SuppressWarnings("unchecked")
BoardMap(int cols, int rows){
numOfCols = cols;
numOfRows = rows;
for(int i = 0; i < numOfCols; i++){
for(int j = 0; j < numOfRows; j++){
((List<GameObject>) cols.get(i)).add(rows.get(j));
}
}
}
@SuppressWarnings("unchecked")
public void addObject(GameObject o, int x, int y){
((List<GameObject>) cols.get(x)).add(y, o);
}
public void removeObject(GameObject o, int x, int y){
}
public boolean occupiedSpace(int x, int y){
return false;
}
}
答案 0 :(得分:3)
可以将板视为行列表,其中每行是单元格列表。您的代码使用两个单元格列表。它应该使用单个列表的单元格列表:
List<List<GameObject>> board = new ArrayList<>();
List<GameObject> firstRow = new ArrayList<>();
firstRow.add(new GameObject()); // first cell of first row
firstRow.add(new GameObject()); // second cell of first row
...
board.add(firstRow);
List<GameObject> secondRow = new ArrayList<>();
secondRow.add(new GameObject()); // first cell of second row
secondRow.add(new GameObject()); // second cell of second row
...
board.add(secondRow);
...
当然,您可以使用嵌套循环执行所有这些步骤:
List<List<GameObject>> board = new ArrayList<>();
for (int r = 0; r < rowCount; r++) {
List<GameObject> row = new ArrayList<>();
for (int c = 0; c < columnCount; c++) {
GameObject cell = new GameObject();
row.add(cell);
}
board.add(row);
}
答案 1 :(得分:0)
您可以将一些默认值加载到二维ArrayList中:
public class Game {
private static List<List<Integer>> gameboard = new ArrayList<List<Integer>>();
public static void main(String[] args) {
gameboard = Arrays.asList(Arrays.asList(1,1,1,1,1),
Arrays.asList(1,1,1,1,1),
Arrays.asList(1,1,1,1,1),
Arrays.asList(1,1,1,1,1),
Arrays.asList(1,1,1,1,1));
printBoard();
incCell(2,2);
System.out.println();
printBoard();
}
public static void incCell(Integer row, Integer col) {
gameboard.get(row).set(col, gameboard.get(row).get(col)+1);
}
public static void printBoard() {
for(List<Integer> row: gameboard) {
for(Integer cell:row) {
System.out.print(cell);
}
System.out.println();
}
}
}
答案 2 :(得分:0)
由于您的电路板是一个固定大小的矩形,因此使用单个数组来表示它而不是列表列表可能更简单。
private GameObject[] board;
BoardMap(int cols, int rows){
numOfCols = cols;
numOfRows = rows;
board = new GameObject[cols*rows];
}
然后,要访问特定的单元格,您可以执行以下操作:
public void setObject(GameObject o, int x, int y){
board[x+y*numOfCols] = o ;
}