在Java中遇到List问题

时间:2014-01-08 16:21:43

标签: java nullpointerexception

我有这堂课:

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()”

上给出错误

为什么用初始化它时它表示为null:

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();

EDIT2:

    public class Project {

        Game game;

        public void listGameVariables() {

            System.out.print(game.attributes.getHowManyNodes());

        }

}

public class Game {

    Attributes attributes = new Attributes();
}

这是我的整个设置。

4 个答案:

答案 0 :(得分:2)

根据您的评论(和您的代码),您的列表中的一个(或两个)必须为空。我会像这样添加一个空检查

howMany += text == null ? 0 : text.size();
howMany += angle == null ? 0 : angle.size();

你可能有另一种方法是“归零”这些字段。

答案 1 :(得分:1)

我已编译并运行此代码,它打印出0而没有NullPointerException。使用您提供的代码无法获得此错误。

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

    public static void main(String[] args) {
        Attributes attributes = new Attributes();
        System.out.print(attributes.getHowManyNodes());
    }

}

答案 2 :(得分:0)

getHowManyNodes()方法的第一个源代码行中设置BreakPoint,以调试模式启动程序,并尝试使用快捷键(Eclipse){{1}找出错误的来源} - > StepInto和F5 - >步距。您提供的来源看起来很好,不应该导致任何问题。通过Eclipse或任何其他IDE调试应用程序,您应该很容易发现此类错误。

答案 3 :(得分:0)

唯一可能发生这种情况的方法是:

在其他地方访问
  1. 角度,并在调用getHowManyNodes()之前将其设置为null。
  2. 角度被另一个您未在代码示例中显示的同名变量“遮蔽”。

调试方法:

  1. 将您的变量设为私有和最终,并查看它们中断的代码,以便您可以看到它们是否在其他地方设置为null。
  2. 将System.out.println(angle)放在角度实例化下的代码块中,也放在构造函数中。

将来如何避免此错误:

  1. 封装您的变量。
  2. 让您的方法保持无效。