为什么这个列表<>抛出NullPointerException?

时间:2015-11-28 02:12:05

标签: java nullpointerexception

所以我已经在这段代码上面停留了一段时间,准备好NullPointerException线程,但仍然无法弄清楚我的代码出了什么问题,所以我转向你。

public class Main {
public static void main(String[] args){     
    /* Making catalog, loading last state */
    Collection catalog = new Collection();      
    try {
        catalog.readFromFile();
    } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace();
    }
catalog.addShip(new Ship("ABC123", "John", "Suzuki", 50));
 }
}

我的Collection类看起来像这样:

public class Collection {
    private List<Ship> shipList;
    private String fileName = "catalog.txt";
    private int income;
    private int space;

public Collection() {
    shipList = new ArrayList<Ship>();
    income = 0;
    space = 500;
    File f = new File("catalog.txt");
    if(!f.exists()) {
        try {
            f.createNewFile();
            writeToFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public void addShip(Ship SHIP){
    space -= SHIP.LENGTH;
    income += SHIP.COST;
    shipList.add(SHIP);
}

public Ship getShip(int INDEX){
    return shipList.get(INDEX);
}

public void writeToFile() throws IOException {
    FileOutputStream f = new FileOutputStream(fileName);
    ObjectOutputStream out = new ObjectOutputStream(f);
    out.writeObject(shipList);
    out.close();        
    }

@SuppressWarnings("unchecked")
public void readFromFile() throws IOException, ClassNotFoundException {
    FileInputStream f = new FileInputStream(fileName);
    ObjectInputStream in = new ObjectInputStream(f);
    shipList = (ArrayList<Ship>)in.readObject();
    in.close();
}

public int getIncome(){
    return income;
}

public int getSpace(){
    return space;
}
}

我的问题是,当我在主catalog.addship()中调用时,我得到nullptr错误。在跟踪控制台错误之后,它说当我调用目录上的addShip()时我得到nullptrexc,从那里我得到错误当我add()发送到集合shipList 1}}。所以我得出结论,这是因为Collection中的shipList是未初始化的。但是在构造函数中我写了shipList = new ArrayList<Ship>();所以它已经被清楚地初始化了。

异常堆栈跟踪如下:

Exception in thread "main" java.lang.NullPointerException
    at collection.Collection.addShip(Collection.java:31)
    at main.Main.main(Main.java:100)

1 个答案:

答案 0 :(得分:6)

在main方法中,正确初始化ArrayList。但是,你做了一个

catalog.readFromFile()

呼叫。在readFromFile()方法中,重新初始化ArrayList

shipList = (ArrayList<Ship>)in.readObject();

in.readObject()返回null。这就是你的shipList变量为空的原因。

希望这有帮助!