检查数组元素是否为空

Check if an element of array is Empty

我的方法 applyBonus() 来自 class BonusEmporiumCity 对象的数组列表中获取奖励对象并将它们应用于 Player 对象。 当我这样写我的函数时,我测试它没有问题:

public class BonusEmporium extends Bonus {
    public BonusEmporium(int cities) {
        this.setBonusType(BonusType.EMPORIUM);
        this.cities=cities;
        setCity(new ArrayList<City>(cities));
    }
    public void applyBonus(Player player){
        Bonus bonus=getCity().get(0).getBonus().get(0);//gets the first bonus from the first 
                                                       //city
        bonus.applyBonus(player);
        Bonus bonus=getCity().get(0).getBonus().get(1);//gets the second bonus from the first 
                                                       //city
        bonus.applyBonus(player);
        Bonus bonus=getCity().get(1).getBonus().get(0);//gets the first bonus from the
                                                       //second city
        bonus.applyBonus(player);
    }

}

问题是当我想 运行 仅当数组列表包含元素时,我如何检查数组中的元素是否为空?

public class BonusEmporium extends Bonus {
    public BonusEmporium(int cities) {
        this.setBonusType(BonusType.EMPORIUM);
        this.cities=cities;
        setCity(new ArrayList<City>(cities));
    }
    public void applyBonus(Player player){
        int i=0,j=0;

            while(j<cities){
                while(getCity().get(j).getBonus().get(i)!=null){//In theory this should 
//verify that the element bonus i from the city j is not empty
//but i get NullPointerException
                    Bonus bonus=getCity().get(j).getBonus().get(i);
                    bonus.applyBonus(player);
                    i++;
                }
                j++;
        }

    }

}

你这样检查元素是否为空:

if(array != null && array.get(index) == null) // element is null when empty

检查整个数组是否为空(没有元素):

if(array != null && array.isEmpty())

很难说清你在问什么,但你应该能够通过更好地处理 message chain 来避免错误。

public void applyBonus(Player player){
    List<City> cities = getCity();
    for(int i = 0; cities != null && i < cities.size(); i++){
        City c = cities.get(i);
        List<Bonus> bonuses = c.getBonus();
        for (int j = 0; bonuses != null && j < bonuses.size(); j++) {
            Bonus b = bonuses.get(j);
            if (b != null)
                b.applyBonus(player);
        }
     }
}

一般来说,java 中的问题是像这样链接 getter:

getCity().get(j).getBonus().get(i)!=null

您可以从这里的 4 个地方获取空指针异常。您可以像这样检查它们:

if (getCity()!=null &&
   getCity().get(j) &&
   getCity().get(j).getBonus() &&
   getCity().get(j).getBonus().get(i)!=null){
....
}

其他方法可能是将整个代码封装在 try - catch 和捕获 NPE 中,这更像是 hack。

我还建议改用 foreach 而不要将数组大小存储在单独的变量中,因为您始终可以使用

获取它
myArr.getSize()

同时检查 java关于 ArrayList 构造函数的文档:

new ArrayList<City>(cities)

因为这可能不是您所期望的

短篇小说:

在构造函数中初始化所有 ArrayList(不指定大小)

使用 foreach 循环

不要将空值放入数组中

不检查空元素应该没问题