Array of Classes NullPointerException

后端 未结 8 1748
悲&欢浪女
悲&欢浪女 2020-12-12 05:17

This is Element class:

public class Element {

    private String elementName;
    private int atomicNumber;
    private String Symbol;
    priv         


        
8条回答
  •  盖世英雄少女心
    2020-12-12 05:44

    You need to create objects. You just created array of object references.

    Element[] element = new Element[103];
    for(int i=0; i<103; i++) {
       element[i] = new Element();
    }
    

    As your element is object (arrays are object) and it is stored on heap. All Element object references are initialized to null value. Due to which you are getting NPEs.

    Element[] element = new Element[103];
    element[0].setElementName("H");  // element[0] is null
    

提交回复
热议问题