0

So, adding stuff to my custom linked list is causing a NullPointerException, and I cannot, for the life of me, figure out why. The purpose of the program is to simulate a chest of drawers, with a list that has the drawers as nodes. The drawers each have a list that includes household objects as nodes.

Here's the relevant bits of code. The error happens when I create a: new ChestOfDrawers(3); in my UI class:

public class ChestOfDrawers{

    private static OwnList chest;  
    private static int[] parametres;

    public ChestOfDrawers (int drawers){
        chest = new OwnList();
        create();
    }

    public static void create(){
        for (int i = 0; i < parametres.length; i++) {
            Object drawer = new Drawer(i, parametres[i]);
            chest.add(i, drawer); //This is causing the error
        }   
    }
}

The Drawer class being referred to here is the class for the drawers. It requires int i as an ID and int parametres as drawer capacity. The parametres[] array gets filled before the additions to the list are made and it includes info for drawer capacity. The linked list in the question (OwnList) is functioning 100% correctly as it is part of a provided course material, it's near identical to Java's own. I tested the class in another test class and it worked fine, I've just made a mistake here somewhere. Please help!

4

1 回答 1

4

问题是您没有初始化参数数组。该字段默认为空。您需要在声明的位置或在静态初始化程序块中对其进行初始化。另外,为什么这两个字段和创建方法是静态的?这些当然看起来像实例状态......

这是一个更好的版本:

public final class ChestOfDrawers{
    private final OwnList chest = new OwnList();  
    private final int[] parametres;

public ChestOfDrawers (int drawers){
    if (drawers < 0) throw new IllegalArgumentException("Drawers may not be negative");
    chest = new OwnList();
    parametres = new int[drawers]; // <-- I'm assuming that's the intended meaning
    initialize();
}        

private void initialize(){
    for(int i = 0; i < parametres.length; i++){
        Object drawer = new Drawer(i, parametres[i]); // <-- parametres[i] will always be 0
        chest.add(i, drawer); 
    }   
}
}

我不确定你需要 parametres 数组实际包含什么(一个新的 int 数组将填充零值) - 但我将把它作为练习留给读者:-)

于 2013-03-26T20:53:55.030 回答