NPE with initialized variable [duplicate]

  • A+
Category:Languages

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) {         this.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 ch.aaa.xxx.yyy.gruppen.plugin.anzeige.beschriftungseinstellungen.BeschriftungssetTableModel.getRowCount(BeschriftungssetTableModel.java:36) at javax.swing.table.DefaultTableModel.setDataVector(DefaultTableModel.java:224) at javax.swing.table.DefaultTableModel.<init>(DefaultTableModel.java:124) at javax.swing.table.DefaultTableModel.<init>(DefaultTableModel.java:106) at javax.swing.table.DefaultTableModel.<init>(DefaultTableModel.java:86) at ch.aaa.xxx.yyy.gruppen.plugin.anzeige.beschriftungseinstellungen.BeschriftungssetTableModel.<init>(BeschriftungssetTableModel.java:18) at ch.aaa.xxx.yyy.gruppen.plugin.anzeige.beschriftungseinstellungen.BeschriftungssetTableModel.main(BeschriftungssetTableModel.java:50) 

 


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?

Comment

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