1

Hi everyone I am trying to add objects to an ArrayList from another class but I have a java.lang.NullPointerException. Here is my code.

public class MLD {

    private ArrayList<Entity> entityList;

    public MLD() {
        this.entityList = entityList;
    }
    public ArrayList<Entity> getEntityList() {
        return entityList;
    }
    public void setEntityList(ArrayList<Entity> entityList) {
        this.entityList = entityList;
    }
    
}
    
public class MLDManaging {
    private MLD mld;

    public MLDManaging() {
        this.mld = new MLD();
    }
    

    public void addEntity(Entity e1) {
            mld.getEntityList().add(e1);
    }
}

And I test it like this in the main:

MLDManaging m = new MLDManaging();
MLD mld =new MLD();
Entity e1 = new Entity("Entity 1", list1);
m.adde(e1);
m.addEntity(e1);

Thank you in advance

2 Answers 2

2

You need to initialize list in constructor this.entityList = new ArrayList<>(); as shown below

public class MLD {

    private ArrayList<Entity> entityList;

    public MLD() {
        this.entityList = new ArrayList<>();
    }
    public ArrayList<Entity> getEntityList() {
        return entityList;
    }
    public void setEntityList(ArrayList<Entity> entityList) {
        this.entityList = entityList;
    }
    
}
Sign up to request clarification or add additional context in comments.

Comments

0

You haven't initialized the list in MLD class.

Better way would be to create a separate method to add to the list rather than calling the getter method and then invoking add.(which is not a clean code approach)

public class MLD {

    private ArrayList<Entity> entityList;
    
    public ArrayList<Entity> getEntityList() {
        return entityList;
    }
    public void addEntity(Entity entity) {
        if(entityList == null) {
            // list would be initialized only when required.
            // This would help reduce unwanted memory usage.
            entityList = new ArrayList<>();
        }
        entityList.add(entity);        
    }    
}

Note : I am not sure why you have created the MLDManaging class. But if it is just to add an entity to the list of MLD object, then I would recommend that the MLDManaging class to be removed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.