繁体   English   中英

如何将自定义对象添加到相同类型的2D数组中

[英]How to add custom made object to a 2D array of the same type

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 有人可以帮忙吗?

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);

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

在Java中,也不能扩展基本类型int以及自动装箱的类Integer

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM