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

时间:2018-04-19 05:45:42

标签: java arrays arraylist multidimensional-array

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

在您的问题中,您要求使用fun container(containerComponent: JPanel = JPanel(), constraints: LC = LC(), setup: JPanel.() -> Unit): JPanel {...} 作为元素。在Java中,无法执行运算符重载。所以&#39; []&#39;不能专门针对从基本类型int[][] grid派生的单元格元素进行定制。您在Java中要求的功能只能通过定义一个类并使用类方法来寻址元素int来实现,即i,jsetElement(int x, int y, boolean value)。在C ++中,可以执行运算符重载。但是,这在某些情况下导致难以阅读的代码,因此Java中省略了该选项。

在Java中,也无法扩展基本类型getElement(int x, int y)以及自动编排的类int