Array of Classes NullPointerException

后端 未结 8 1712
悲&欢浪女
悲&欢浪女 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:20

    Creating new object arrays will yield arrays filled with null. If you need to have objects, you will have to iterate over the array after its creation and populate it with new instances.

    0 讨论(0)
  • 2020-12-12 05:21

    Declaring an array like initialises the array object, but not the elements of the array. You need to create an Element object at each index of the array.

    element[0] = new Element();
    element[0].setElementName("H");
    
    0 讨论(0)
  • 2020-12-12 05:28

    You have not initialized element[0] . You need to initialize it first, in fact every array element if you intent to use them.

    element[0]=new Element();
    

    or you can initialize all of them using loop

      for(int i=0;i<element.length;i++)
      {
        element[i]=new Element();
      }
    
    0 讨论(0)
  • 2020-12-12 05:29

    Between those two lines

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

    you need to create element[0], that is to build a new instance of Element. In your code element[0] is null, hence the NullPointerException when you call setElementName.

    0 讨论(0)
  • 2020-12-12 05:35

    The Problem is in the part:

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

    Your accessing the first element without creating it before that. you create the array but it doesnt containt automatically new objects of the type used, you have to declare these explicitly, for example:

    element[0] = new element();
    

    And then you can use the object.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题