Reputation:
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
Upvotes: 1
Views: 367
Reputation: 4935
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.
Upvotes: 0
Reputation: 3766
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;
}
}
Upvotes: 2