简体   繁体   中英

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

I'm trying to add Cell objects to my int grid using their value inside the program. I have declared a Cell[][] cellGrid = new Cell[20][20] inside my class i want to add Cell objects to that grid. But it should be same as the int[][] grid . Can someone help with this.

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

In your question, you asked to use int[][] grid as element. In Java, it is not possible to perform operator overloading . So '[]' cannot be tailored specifically to a cell element, derived from the primitive type int . The functionality you asked for can in Java only be achieved by defining a class and using class methods for addressing the element i,j , ie setElement(int x, int y, boolean value) and getElement(int x, int y) . In C++, operator overloading can be performed. However, this in some cases led to difficult-to-read code, and so this option was omitted in Java.

In Java it is also not possible to extend a primitive type int , as well as the autoboxed class Integer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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