Home > front end >  Adding objects to an array list - "Cannot invoke xxx.add because yyy is null"
Adding objects to an array list - "Cannot invoke xxx.add because yyy is null"

Time:12-19

I have a class of objects:

public class SubObjects {
    
    int depth;
    
    public SubObjects(int d) {
        this.depth = d;
    }
}

And then another class of objects:

import java.util.ArrayList;

public class Objects {
    
    private int height;
    private int width;
    ArrayList<SubObjects> liste;
    
    public Objects(int h, int w) {
        this.height = h;
        this.width = w;
    }
}

The idea here is that each object should be able to hold a height value, a width value and a list of SubObjects.

E.g. = 2,4,[SubObject1, SubObject2]

The following being the main class:

import java.util.*;

public class Tryout {
    
    public static void main(String[] args) {
        SubObjects S1 = new SubObjects(7);
        SubObjects S2 = new SubObjects(9);
        
        Objects O1 = new Objects(2,4);
        O1.liste.add(S1);
        O1.liste.add(S2);
        
        System.out.println(O1);
    }
}

First I create two SubObjects.

Then I create an Object with the ints 2 and 4.

Where everything goes astray is the next line:

O1.liste.add(S1);

The error code given:

Cannot invoke "java.util.ArrayList.add(Object)" because "O1.liste" is null

Now I get that the array list is null, I have not added anything yet of course, but why can't I add anything to it?

I appreciate answers that assume I am an untalented 8th grader.

CodePudding user response:

liste is not initilized. In other words, it isn't an ArrayList - it's a null reference. Since there's no object there, you can't call any methods on it.

To solve the issue, you could initialize liste in the constructor:

public Objects(int h, int w) {
    this.height = h;
    this.width = w;
    this.liste = new ArrayList<>();
}

CodePudding user response:

liste was never initialized. Either initialize as below or in the constructor.

public class Objects {
    
    private int height;
    private int width;
    ArrayList<SubObjects> liste = new ArrayList<>(); // <===add this
    
    public Objects(int h, int w) {
        this.height = h;
        this.width = w;
    }
}
  • Related