我有这门课:
public class Attributes {
List text = new ArrayList();
List angle = new ArrayList();
public Attributes() {
}
public int getHowManyNodes() {
int howMany = 0;
howMany += text.isEmpty() ? 0 : text.size();
howMany += angle.isEmpty() ? 0 : angle.size();
return howMany;
}
}
当我这样做时:
Attributes attributes = new Attributes();
System.out.print(attributes.getHowManyNodes());
它给出线程“main”java.lang.NullPointerException中的异常
奇怪的是,它只在“angle.isEmpty()”上给出错误,而不在“text.isEmpty()”
上给出错误为什么当我初始化它时它说它为空:
List angle = new ArrayList();
编辑1:
Full error:
Exception in thread "main" java.lang.NullPointerException
at projectmerger1.Attributes.getHowManyNodes(Attributes.java:55)
at projectmerger1.Project.listGameVariables(Project.java:235)
at projectmerger1.ProjectMerger1.main(ProjectMerger1.java:289)
Java Result: 1
小修改:
属性类中的第 55 行是
howMany += angle.isEmpty() ? 0 : angle.size();
编辑2:
public class Project {
Game game;
public void listGameVariables() {
System.out.print(game.attributes.getHowManyNodes());
}
}
public class Game {
Attributes attributes = new Attributes();
}
这是我的整个设置。
最佳答案
根据您的评论(和您的代码),您的列表中的一个(或两个)必须为空。我会添加一个像这样的空检查
howMany += text == null ? 0 : text.size();
howMany += angle == null ? 0 : angle.size();
您可能有另一种方法来“清空”这些字段。
关于java - Java 中的 List 存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21001072/