简体   繁体   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;
}

I'm trying to add Cell objects to my int grid using their value inside the program. 我正在尝试使用程序中它们的值将Cell对象添加到我的int网格中。 I have declared a Cell[][] cellGrid = new Cell[20][20] inside my class i want to add Cell objects to that grid. 我在类中声明了一个Cell[][] cellGrid = new Cell[20][20] ,我想将Cell对象添加到该网格中。 But it should be same as the int[][] grid . 但是它应该与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. 在您的问题中,您要求使用int[][] grid作为元素。 In Java, it is not possible to perform operator overloading . 在Java中,不可能执行运算符重载 So '[]' cannot be tailored specifically to a cell element, derived from the primitive type int . 所以'[]'不能专门针对从原始类型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) . 您要求的功能只能在Java中通过定义一个类并使用类方法来寻址元素i,j ,即setElement(int x, int y, boolean value)getElement(int x, int y) In C++, operator overloading can be performed. 在C ++中,可以执行运算符重载。 However, this in some cases led to difficult-to-read code, and so this option was omitted in Java. 但是,在某些情况下,这会导致代码难以阅读,因此Java中省略了此选项。

In Java it is also not possible to extend a primitive type int , as well as the autoboxed class Integer . 在Java中,也不能扩展基本类型int以及自动装箱的类Integer

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

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