简体   繁体   中英

Add objects to an ArrayList from another class

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

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;
    }
    
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM