You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建Rows×Cols规格的Box类实例二维ArrayList网格

实现Box类的二维网格访问方案

嘿,我来帮你搞定这个网格实现的问题!首先得明确一点:Java本身的语法限制了我们不能直接写出coord.get(5)(6)这种调用,但我们有几种非常接近且实用的方案,下面一步步给你拆解:

1. 最通用的二维ArrayList实现

这是Java里构建二维网格最常用的方式,不需要额外自定义类,代码简洁易维护:

初始化网格

int totalRows = 10; // 替换成你需要的行数
int totalCols = 10; // 替换成你需要的列数
ArrayList<ArrayList<Box>> coord = new ArrayList<>();

// 循环创建每一行,并填充Box实例
for (int rowIdx = 0; rowIdx < totalRows; rowIdx++) {
    ArrayList<Box> currentRow = new ArrayList<>();
    for (int colIdx = 0; colIdx < totalCols; colIdx++) {
        // 这里可以根据Box的构造函数传入参数,比如new Box(rowIdx, colIdx)
        currentRow.add(new Box());
    }
    coord.add(currentRow);
}

访问单元格

要获取第5行第6列的Box,只需要链式调用两次get:

Box targetBox = coord.get(5).get(6);

这种写法是Java开发者的共识,别人看你的代码一眼就能懂,非常推荐。


2. 更简洁的双参数访问方案

如果你觉得两次get有点繁琐,可以自定义一个Grid类,封装二维ArrayList,并提供一个接收行、列索引的get方法:

自定义Grid类

import java.util.ArrayList;

public class Grid {
    private final ArrayList<ArrayList<Box>> internalGrid;

    // 构造函数:直接初始化指定大小的网格
    public Grid(int rows, int cols) {
        internalGrid = new ArrayList<>(rows);
        for (int i = 0; i < rows; i++) {
            ArrayList<Box> row = new ArrayList<>(cols);
            for (int j = 0; j < cols; j++) {
                row.add(new Box());
            }
            internalGrid.add(row);
        }
    }

    // 直接通过行、列索引获取Box实例
    public Box get(int rowIndex, int colIndex) {
        return internalGrid.get(rowIndex).get(colIndex);
    }

    // 可选:提供获取整行的方法
    public ArrayList<Box> getRow(int rowIndex) {
        return internalGrid.get(rowIndex);
    }
}

使用方式

初始化和访问都变得更简洁:

Grid coord = new Grid(10, 10);
Box targetBox = coord.get(5, 6); // 一行搞定!

关于coord.get(5)(6)的说明

这里得给你提个醒:Java不支持这种直接的函数式调用语法(也就是让方法返回的对象直接用()调用),这是Kotlin、Python这类语言的特性。如果强行用函数式接口模拟,会写出coord.getRow(5).apply(6)这种代码,反而降低了可读性,完全没必要。

所以我的建议是:优先用第一种通用方案,或者第二种自定义Grid的方案,这两种都是Java生态里最合理的实现方式。

内容的提问来源于stack exchange,提问作者bramvdwalle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:21:38