NPE with initialized variable [duplicate]

  • A+

This question already has an answer here:

Can someone explain to me why I am getting a NullPointerException in the getRowCount() method? The variable is initialized with an empty ArrayList...

public class BeschriftungssetTableModel extends DefaultTableModel {      private static final long serialVersionUID = -4980235976337188354L;      private List<BeschriftungssetBean> data = new ArrayList<>();       public void setData(List<BeschriftungssetBean> data) { = data;     }      @Override     public int getColumnCount() {         return 1;     }      @Override     public int getRowCount() {         return data.size();     }      @Override     public Object getValueAt(int row, int column) {         return data.get(row).getBezeichnung();     }      @Override     public String getColumnName(int column) {         return "Bezeichnung";     }      public static void main(String[] args) {         BeschriftungssetTableModel beschriftungssetTableModel = new BeschriftungssetTableModel();         beschriftungssetTableModel.getRowCount();     } }    public class BeschriftungssetBean {     private String objId;     private String bezeichnung;      public String getBezeichnung() {         return bezeichnung;     }      public void setBezeichnung(String bezeichnung) {         this.bezeichnung = bezeichnung;     }      public String getObjId() {         return objId;     }      public void setObjId(String objId) {         this.objId = objId;     } } 

Exception in thread "main" java.lang.NullPointerException at at javax.swing.table.DefaultTableModel.setDataVector( at javax.swing.table.DefaultTableModel.<init>( at javax.swing.table.DefaultTableModel.<init>( at javax.swing.table.DefaultTableModel.<init>( at<init>( at 


The constructor of DefaultTableModel calls getRowCount before the subclass had a chance to initialize its content, thus leading to NPE with your implem. This is a bad design of the base class, as calling overridable methods from within a constructor is considered a bad practice, but hey, Swing API has quite a few of these :)

Cf. What's wrong with overridable method calls in constructors?


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: