nullpointerexception array.length java

时间:2016-01-24 18:28:29

标签: java arrays nullpointerexception

每当我尝试访问我的阵列时,我都会得到一个NPE。即使调用.length属性也会给我一个NPE。任何帮助,将不胜感激。这是我的构造函数和保持失败的方法。

public SkierList() {
    Skier[] skiers= new Skier[INITIAL_CAP];
    for (int i = 0; i < skiers.length;i++){
        skiers[i] = new Skier("");
    }
    int count = 0;

}

public void add(Skier newSkier) {   
    if (this.size() < skiers.length)
    {
        skiers[count] = new Skier(newSkier.getName(), newSkier.getLevel());
        count++;
    }
}

代码编译但是在skiers.length中抛出NPE

2 个答案:

答案 0 :(得分:0)

全球定义滑雪者:

public Skier[] skiers= new Skier[INITIAL_CAP];

答案 1 :(得分:0)

您必须通过在构造函数中重新声明变量来隐藏变量。不要这样做,因为它将字段留空。所以不是这样:

public class SkierList() {
    private Skier[] skiers; // this remains null

    public SkierList() {
        // you're re-declaring the skiers variable here
        // so only this local variable is non-null
        Skier[] skiers= new Skier[INITIAL_CAP];

        // ....
    }
}

而是

public class SkierList() {
    private Skier[] skiers; 

    public SkierList() {
        // Skier[] skiers= new Skier[INITIAL_CAP]; // Don't do this
        skiers = new Skier[INITIAL_CAP];  // note the difference
    }
}

public class SkierList() {
    private Skier[] skiers = new Skier[INITIAL_CAP];

    public SkierList() {
        // Skier[] skiers= new Skier[INITIAL_CAP];
    }
}