NullPointerException when Creating an Array of objects

57,762

Solution 1

You created the array but didn't put anything in it, so you have an array that contains 5 elements, all of which are null. You could add

boll[0] = new ResultList();

before the line where you set boll[0].name.

Solution 2

ResultList[] boll = new ResultList[5];

creates an array of size=5, but does not create the array elements.

You have to instantiate each element.

for(int i=0; i< boll.length;i++)
    boll[i] = new ResultList();

Solution 3

I think by calling

ResultList[] boll = new ResultList[5];

you created an array which can hold 5 ResultList, but you have to initialize boll[0] before you can set a value.

boll[0] = new ResultList();

Solution 4

As many have said in the previous answers, ResultList[] boll = new ResultList[5]; simply creates an array of ResultList having size 5 where all elements are null. When you are using boll[0].name, you are trying to do something like null.name and that is the cause of the NullPointerException. Use the following code:

public class Test {
    public static void main(String[] args){
        ResultList[] boll = new ResultList[5];

        for (int i = 0; i < boll.length; i++) {
            boll[i] = new ResultList();
        }

        boll[0].name = "iiii";
   } 
}

Here the for loop basically initializes every element in the array with a ResultList object, and once the for loop is complete, you can use

boll[0].name = "iiii";

Solution 5

ResultList p[] = new ResultList[2];

By writing this you just allocate space for a array of 2 elements. You should initialize the reference variable by doing this:

for(int i = 0; i < 2; i++){
    p[i] = new ResultList();
 }
Share:
57,762
Admin
Author by

Admin

Updated on August 01, 2022

Comments

  • Admin
    Admin almost 2 years

    I have been trying to create an array of a class containing two values, but when I try to apply a value to the array I get a NullPointerException.

    public class ResultList {
        public String name;
        public Object value;
    }
    

    public class Test {
        public static void main(String[] args){
            ResultList[] boll = new ResultList[5];
            boll[0].name = "iiii";
        }
    }
    

    Why am I getting this exception and how can I fix it?