[英]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.大家好,我正在尝试从另一个 class 向 ArrayList 添加对象,但我有一个 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<>();
您需要在构造函数中初始化列表
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.您尚未初始化
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)更好的方法是创建一个单独的方法来添加到列表中,而不是调用
getter
方法然后调用add
。(这不是一个干净的代码方法)
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.注意:我不确定您为什么创建了
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.但如果只是在
MLD
object 的列表中添加一个实体,那么我建议将MLDManaging
class 删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.