Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException on list.add

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);     }  } 
like image 956
novicePrgrmr Avatar asked Mar 08 '11 00:03

novicePrgrmr


People also ask

How do you handle a NullPointerException in a list?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

What is the most likely cause of NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

How do I ignore the NullPointerException?

Answer: Some of the best practices to avoid NullPointerException are: Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null. Use valueOf() instead of toString() ; and both return the same result.

Is it good practice to throw NullPointerException?

​ And ruled that yeah, it was OK for an application to throw an NPE. Back to today: a dev reviewed the pull request from another one, found out it threw an NPE and ruled it was bad practice.


1 Answers

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

protected List<EventSeat> modelData = new ArrayList<EventSeat>(); 
like image 77
Erik Avatar answered Oct 02 '22 14:10

Erik