NullPointerException on list.add

2020-02-26 15:39发布

I am getting a NullPointerException at the modelData.add(i, es) method. I know from debugging that es isn't null. I'm really confused, thanks.

public class EventTableModel extends AbstractTableModel {

    //private int rowCount = 0;
    protected List<EventSeat> modelData;
    private static final int COLUMN_COUNT = 3;
    private Event e;
    Event j = GUIpos.m;
    int i = 1;

public EventTableModel(Event e) {
    this.e = e;
    try {
        System.out.println(modelData);
        for (EventSeat es : e.getEventSeats()) {
            modelData.add(i, es);
            i++;
        }
    } catch (DataException ex) {
        Logger.getLogger(EventTableModel.class.getName()).log(Level.SEVERE, null, ex);
    }

}

3条回答
戒情不戒烟
2楼-- · 2020-02-26 15:39

You need to initialize a List to not get the NullPointerException.

protected List<EventSeat> modelData = new ArrayList<EventSeat>();
查看更多
Animai°情兽
3楼-- · 2020-02-26 15:51

On the first look, seems like modelData has not been instantiated. I would instantiate the modelData like:

protected List<EventSeat> modelData = new ArrayList<EventSeat>();

FYI.. In Java 7 there will be a new syntax you can use- someObject?.doSomething();

查看更多
走好不送
4楼-- · 2020-02-26 16:02

Try

protected List<EventSeat> modelData = new ArrayList<EventSeat>(); 
查看更多
登录 后发表回答