检查数组 java

checking an array java

我正在使用像地图一样的二维数组,我有一个设定点 x 和 y,我需要检查周围区域 (+1) 中的三个对象,食物、对象和 space。我考虑过使用 map[x+1][y+1] 如下所示,但是我必须多次重复此状态。

if (map[x+1][y+1] == Item.O)
{
    System.out.println("Object is in the way.");
}

if (map[x+1][y+1] == Item.F)
{
    System.out.println("Food is in the way.");
}

有没有其他方法可以做到这一点,我知道有一个 switch 语句,但我认为这行不通。任何帮助将不胜感激:)

假设 Item 是一个 enum,你确实可以使用 switch 语句:

switch(map[x+1][y+1]) {
   case Item.O : System.out.println("Object is in the way."); break;
   case Item.F : System.out.println("Food is in the way."); break;
   ...
}

但是,更灵活的解决方案是不在数组中存储 enum,而是实现提供所需方法的通用接口的真实对象。然后实现不同的 classes 来实现对象的不同行为。

您的 class 层次结构可能如下所示:

interface PrintText {
    void printText();
}

class Food implements PrintText {
    public void printText() {
       System.out.println("Food is in the way.");
    }
}

class SomeObject implements PrintText {
    public void printText() {
       System.out.println("Object is in the way.");
    }
}

然后您可以像这样初始化数组:

// initialize array
PrintText[][] map = new PrintText[WIDTH][HEIGHT];
map[0][0] = new Food();
map[0][1] = new SomeObject();
...

然后像这样调用方法,没有任何 switchif 语句 - 多态性会处理它:

// call the method
map[x+1][y+1].printText();

附带说明一下,不要使用原始数组。请改用 class 之类的集合 ArrayList