【问题标题】:How to add custom made object to a 2D array of the same type如何将自定义对象添加到相同类型的二维数组
【发布时间】:2018-04-19 05:45:41
【问题描述】:
public static boolean[][] random(int[][] grid) {
    boolean[][] a = new boolean[20][20];
    for (int i = 0; i < grid1.length; i++) {
        for (int j = 0; j < grid1.length; j++) {
            Cell[] cellArray = null;
            if (grid1[i][j] == 0) {
                a[i][j] = false;                   
            } else if (grid1[i][j] == 1) {
                a[i][j] = false;
                Cell cell = new Cell(i, j, 1);
            } else if (grid1[i][j] == 3) {
                a[i][j] = false;
                Cell cell = new Cell(i, j, 3);
            } else if (grid1[i][j] == 4) {
                a[i][j] = true;
                Cell cell = new Cell(i, j, 4);
            } else if (grid1[i][j] == 5) {
                a[i][j] = false;
            }

        }
    }
    return a;
}

我正在尝试使用它们在程序中的值将 Cell 对象添加到我的 int 网格中。我在我的类中声明了一个Cell[][] cellGrid = new Cell[20][20],我想将 Cell 对象添加到该网格中。但它应该与int[][] grid 相同。有人可以帮忙吗。

【问题讨论】:

  • 请不要将变量命名为a
  • 您能否解释一下“我正在尝试使用它们的值将 Cell 对象添加到我的 int 网格中”。显然,您可以将Cell 对象存储在int 网格中,所以您的意思是将Cell 的整数字段添加到int[][] 变量中?
  • "我想将 Cell 对象添加到该网格。但它应该与 int[][] 网格相同" --> 你想将 int[][] 网格的值添加到细胞对象?你也可以发布 Cell 课程吗?
  • 类细胞 { int x, y; // 坐标 double gCost = 0; // G : 到起点的距离 double heuristicCost = 0; // H : 到终点的距离(近似值) double finalCost = 0; // F = G + H 单元格父级; // 单元格,在当前单元格之前访问过 int 权重;单元格(int x,int y){ this.x = x;这个.y = y; }
  • 公共单元格(int x,int y,int weight){ this.x = x;这个.y = y; this.weight = 重量; }

标签: java arrays arraylist multidimensional-array


【解决方案1】:
Cell[][] grid= new Cell[20][20];
for(int i=0;i<grid.length;i++){
    for(int j=0;j<grid.length;j++){   
       int temp= integer_array[i][j];
       grid[i][j]= new Cell(temp);

       //grid[i][j] will be an object of Cell class and any member of the class 
       //can be called 
    }
}
System.out.println(grid[0][1].data);

【讨论】:

  • 这种方式有点困难,我尝试过这种方式,但我需要更短的代码:(
【解决方案2】:

在您的问题中,您要求使用 int[][] grid 作为元素。在 Java 中,不可能执行 运算符重载。因此,'[]' 不能专门针对从原始类型 int 派生的单元格元素进行定制。您要求的功能只能通过定义一个类并使用类方法来寻址元素i,j 来实现,即setElement(int x, int y, boolean value)getElement(int x, int y)。在 C++ 中,可以执行运算符重载。但是,这在某些情况下会导致代码难以阅读,因此在 Java 中省略了此选项。

在 Java 中,也无法扩展基本类型 int,以及自动装箱类 Integer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 2016-07-01
    相关资源
    最近更新 更多