2014-08-31 60 views
0

我以爲我明白NullPointerException,但顯然不是。在這裏,這將引發錯誤: (main是一類)爲什麼鏈式聲明之後是實例化會導致NullPointerException?

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

TopicActionWeight是一個列表。這裏是我的清單聲明:

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

我聲明的列表不是指針,它們是?他們創造了..

是的,我已經試過new ArrayList<Float>();

+0

可能'getSelectedItem()'返回null。甚至是'actionGenreWeightCombo'(這就是我討厭鏈接函數調用的原因之一,因爲你現在從來沒有發生過這樣的錯誤) – 2014-08-31 10:10:01

+1

首先,Java語言中沒有「指針」。但是,所有對象通常都是使用指針**實現的。** – 2014-08-31 10:10:25

回答

1

通過執行以下行,你只申報所有相應的ArrayList,但爲什麼你topicActionWeight爲空,因此不進行初始化沒有人,除了topicSimulationWeight這是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<>(); 
+0

謝謝!我的'密碼夥伴'告訴我,如果我在一個「聲明」中做到這一點,速度更快,效率更高。 – user3902017 2014-08-31 10:20:04

+1

從現在開始,你的代碼好友用一粒鹽來說吧。 – 2014-08-31 10:25:45

相關問題