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

如何将自定义对象添加到同类型二维数组?附相关Java代码

如何将自定义对象添加到同类型的二维数组中?

我来帮你搞定这个问题——把自定义的Cell对象存入同类型的二维数组里。先看看你现有代码里的几个问题,再给你修正后的完整实现。

你当前代码里的问题

  • 方法参数是grid,但循环里误用了未定义的grid1变量,这会导致编译错误
  • 声明了Cell[] cellArray = null;但没有初始化二维的Cell数组,而且创建的Cell实例只是临时对象,没有被存入任何数组
  • 条件判断末尾的grid1[i][j] =...是赋值操作(=)而非比较操作(==),这是语法错误
  • 没有处理数组边界的异常情况,比如grid为null或者行长度不一致的情况

正确的实现步骤

  1. 首先确保你有一个合法的Cell类定义(如果还没有的话)
  2. 创建与输入grid尺寸匹配的Cell[][]二维数组
  3. 遍历输入grid的每个元素,根据值创建对应的Cell对象并赋值到Cell[][]数组的对应位置
  4. 同步处理你需要的boolean[][]数组逻辑

完整代码示例

第一步:定义Cell类

class Cell {
    private int x;
    private int y;
    private int type;

    // 构造方法
    public Cell(int x, int y, int type) {
        this.x = x;
        this.y = y;
        this.type = type;
    }

    // 可选:添加getter方法方便后续获取属性
    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getType() {
        return type;
    }
}

第二步:修正后的处理方法

这个方法会同时返回boolean[][]数组和填充好的Cell[][]数组:

import java.util.AbstractMap;
import java.util.Map;

public class GridProcessor {
    public static Map.Entry<boolean[][], Cell[][]> processGrid(int[][] grid) {
        // 先做参数校验,避免空指针或尺寸不匹配
        if (grid == null) {
            throw new IllegalArgumentException("输入的grid不能为null!");
        }
        int rows = grid.length;
        if (rows == 0) {
            throw new IllegalArgumentException("输入的grid不能是空数组!");
        }
        int cols = grid[0].length;

        // 初始化两个结果数组
        boolean[][] boolGrid = new boolean[rows][cols];
        Cell[][] cellGrid = new Cell[rows][cols];

        // 遍历每个网格位置
        for (int i = 0; i < rows; i++) {
            // 检查每行的列数是否一致
            if (grid[i].length != cols) {
                throw new IllegalArgumentException("第" + i + "行的列数与第一行不匹配!");
            }
            for (int j = 0; j < cols; j++) {
                int cellValue = grid[i][j];
                switch (cellValue) {
                    case 0:
                    case 1:
                    case 3:
                        boolGrid[i][j] = false;
                        cellGrid[i][j] = new Cell(i, j, cellValue);
                        break;
                    case 4:
                        boolGrid[i][j] = true;
                        cellGrid[i][j] = new Cell(i, j, cellValue);
                        break;
                    default:
                        // 处理未知值的情况,这里默认设为false和null,你可以根据需求调整
                        boolGrid[i][j] = false;
                        cellGrid[i][j] = null;
                        System.out.println("警告:位置(" + i + "," + j + ")的未知值" + cellValue);
                        break;
                }
            }
        }
        // 返回两个结果,用AbstractMap.SimpleEntry来封装
        return new AbstractMap.SimpleEntry<>(boolGrid, cellGrid);
    }

    // 测试用例
    public static void main(String[] args) {
        int[][] testGrid = {
                {0, 1, 3},
                {4, 0, 1}
        };
        Map.Entry<boolean[][], Cell[][]> result = processGrid(testGrid);
        boolean[][] boolResult = result.getKey();
        Cell[][] cellResult = result.getValue();

        // 打印测试结果
        for (int i = 0; i < boolResult.length; i++) {
            for (int j = 0; j < boolResult[i].length; j++) {
                System.out.print("位置(" + i + "," + j + "): ");
                System.out.print("bool值=" + boolResult[i][j] + ", ");
                Cell cell = cellResult[i][j];
                if (cell != null) {
                    System.out.println("Cell类型=" + cell.getType());
                } else {
                    System.out.println("Cell为空");
                }
            }
        }
    }
}

关键要点

  • 初始化二维数组:必须先指定Cell[][]的行数和列数,不能直接声明为null,否则无法赋值
  • 对象赋值:创建Cell实例后,直接赋值给cellGrid[i][j],这样就把对象存入二维数组的对应位置了
  • 参数校验:添加参数校验可以避免运行时出现空指针或数组越界异常,让代码更健壮
  • 简洁性:用switch-case替代多个else-if,逻辑更清晰,也更容易扩展新的cell类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:57:54