为什么链接声明后跟实例化会导致NullPointerException?

时间:2014-08-31 10:08:33

标签: java

我以为我理解NullPointerException,但显然不是。{这会抛出一个错误: (main是一个类)

main.topicActionWeight.add(
    Float.parseFloat(this.actionGenreWeightCombo.getSelectedItem().toString()));

TopicActionWeight是一个列表。这是我对清单的声明:

public static List<Float> topicActionWeight,
        topicAdventureWeight,
        topicRPGWeight,
        topicStrategyWeight,
        topicSimulationWeight = new ArrayList<>();

我声明的列表不是指针,是吗?他们被创造..

是的,我尝试过new ArrayList<Float>();

1 个答案:

答案 0 :(得分:1)

通过执行下面的行,你只是声明所有相应的arraylists,但是除了topicSimulationWeight之外没有初始化它们,这就是你的topicActionWeight为null并因此是NPE的原因。

public static List<Float> topicActionWeight,
        topicAdventureWeight,
        topicRPGWeight,
        topicStrategyWeight,
        topicSimulationWeight = new ArrayList<>();

正确的初始化方法是: -

public static List<Float> topicActionWeight = new ArrayList<>();
public static List<Float> topicAdventureWeight = new ArrayList<>();
public static List<Float> topicRPGWeight = new ArrayList<>();
public static List<Float> topicStrategyWeight = new ArrayList<>();
public static List<Float> topicSimulationWeight = new ArrayList<>();