简体   繁体   English

如何检查2D对象数组是否包含某个对象? (Java)

[英]How to check if a 2D object array contains a certain object? (Java)

public class Maze {
    private static final int Max_Maze_Row=20;
    private static final int Max_Maze_Column=50;
    public static Entity[][] maze =new Entity[Max_Maze_Row][Max_Maze_Column];


    public Maze(){

    }

    public static void create(String filename) throws FileNotFoundException{
        Scanner fileinput=new Scanner(new FileInputStream(filename));
        fileinput.useDelimiter("");

        while(fileinput.hasNextLine()){
            for(int row=0;row<Max_Maze_Row;row++){
                String line_content=fileinput.nextLine();
                for(int col=0;col<Max_Maze_Column;col++){
                    if(line_content.charAt(col)=='*'){
                        maze[row][col]=new Wall('*',row,col);
                    }
                    if(line_content.charAt(col)==' '){
                        maze[row][col]=new Space(' ',row,col);
                    }
                }    
            }
        }
}
public abstract class Entity {
    protected char symbol;
    protected int row;
    protected int col;

    Entity(char symbol, int row, int col){
        this.symbol=symbol;
        this.row=row;
        this.col=col;
    }

    public abstract void create();

    public char Entity_put(char newEntity, int newRow, int newCol){
        char oldEntity=this.symbol;
        this.symbol=newEntity;
        this.row=newRow;
        this.col=newCol;
        System.out.println(oldEntity);
        return oldEntity;
    }

}
public class Wall extends Entity{
    public Wall(char symbol,int row,int col){
        super(symbol,row,col);
    }
    public void create(){

    }

}

I also have a class Space which inherits from the Entity superclass. 我还有一个继承自Entity超类的Space类。 Its essentially ' '. 其本质上是''。 So what happens is, the program reads from a text file, then creates wall and space entities, which have a specific row, column, character value. 因此,发生的情况是该程序从文本文件读取,然后创建具有特定行,列和字符值的墙和空间实体。 And these entities are stored in the Entity[][] maze. 这些实体存储在Entity [] []迷宫中。 However, how can I reference these objects? 但是,如何引用这些对象? For example, how can I know how many wall objects there are in the maze array? 例如,如何知道迷宫阵列中有多少个墙对象? Basically, what I am trying to do is something along the lines of: Randomly pick an entity that is not a wall (ie space entity). 基本上,我想做的事情大致如下:随机选择一个不是墙的实体(即空间实体)。 Do something. 做一点事。

You can reference the objects in the multidimensional array using their index, then you can use instanceof to identify if they are Wall or Space.....you can write something like below. 您可以使用它们的索引引用多维数组中的对象,然后可以使用instanceof标识它们是Wall还是Space .....您可以编写如下内容。 Below is a code to count the number of Walls' and Spaces' in your Maze multi dimensional array. 下面是一个代码,用于计算迷宫多维数组中“墙”和“空间”的数量。

public static void count(Maze[][] maze) {
    int wallCount = 0;

    int spaceCount = 0;

    if (maze != null)

        for (int i = 0; i < maze.length; i++) {

            if (maze[i] != null)
                for (int j = 0; j < maze[i].length; j++) {

                    if (maze[i][j] instanceof Wall)
                        wallCount++;
                    if (maze[i][j] instanceof Space)
                        spaceCount++;
                }

        }

}

Edit: I think you can have another abstract function such as performAction in Entity class, and override this method in each subclass, namely Wall and Space in this case. 编辑:我认为您可以在Entity类中具有另一个抽象函数,例如performAction ,并在每个子类中覆盖此方法,在这种情况下,即WallSpace When you traverse through the array later, you can just do 以后遍历数组时,您可以

Entity entity = maze[row][col];
entity.performAction();

Java will figure out which subclass's performAction to use at runtime. Java将确定在运行时使用哪个子类的performAction

=========================================================================== One option is to store two additional ArrayList as fields. ================================================== =========================一种选择是将两个额外的ArrayList作为字段存储。 For instance, 例如,

List<Entity> walls;
List<Entity> spaces;

Initialize them inside the constructor. 在构造函数中初始化它们。

public Maze() {
    this.walls = new ArrayList<Entity>();
    this.spaces = new ArrayList<Entity>();
}

Inside the most inner loop in Maze.create() , you can use these to lists to track walls and spaces. Maze.create()的最内层循环中,您可以使用它们来跟踪墙壁和空间。

for(int col = 0; col < Max_Maze_Column; col++){
    if (line_content.charAt(col) == '*') {
        maze[row][col] = new Wall('*', row, col);
        this.walls.add(maze[row][col]);
    } 

    if (line_content.charAt(col) == ' ') {
        maze[row][col] = new Space(' ', row, col);
        this.spaces.add(maze[row][col]);
    }
}

You can get every single wall and space through index access. 您可以通过索引访问获得所有墙和空间。 For size, just call walls.size() and spaces.size() . 对于大小,只需调用walls.size()spaces.size() For random access, you can use 对于随机访问,您可以使用

// int max = walls.size() or spaces.size()
Random seed = new Random();
// Generate a random integer from 0 to (max - 1)
int index = seed.nextInt(max);

The second option may be using the instanceof operator when you traverse through the array later. 当您稍后遍历数组时,第二个选项可能是使用instanceof运算符。 For instance, 例如,

Entity entity = maze[row][col];

if (entity instanceof Wall) {
    Wall wall = (Wall) entity;
    // do something with wall

} else if (entity instanceof Space) {
    Space space = (Space) entity;
    // do something with space
}

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

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