[英]Adding “double” to List<Double> doubleList
我在將Double
存儲到List<Double>
遇到麻煩。
int idx = 0;
String [] documentText = getText();
for(String word : wordList) {
wordsDistributionList.put(word, new ArrayList<Double>());
}
// ...
if ( wordsDistributionList.containsKey(word.toLowerCase()) == true ) {
List<Double> dbls = wordsDistributionList.get(word);
double dbl = ((double)idx/(double)documentText.length);
dbls.add(new Double(dbl));
break;
}
這樣做會導致以下結果:
Exception in thread "main"
java.lang.NullPointerException
at worddistribution.DocumentsStatistics.getWordDistribution(DocumentsStatistics.java:57)
at worddistribution.Main.main(Main.java:34)
有人可以告訴我如何將Double
存儲在列表中嗎?
您需要初始化您的列表,如果
List<Double> dbls = wordsDistributionList.get(word);
返回null,則當您嘗試添加Double時,您的列表將為null。
確保wordsDistributionList.get(word)
如果返回,然后顯式初始化列表,則不返回null。
就像@ZouZou說的嘗試:
List<Double> dbls = wordsDistributionList.get(word.toLowerCase());
但是,如果仍然返回null,那么您的問題是您沒有初始化要返回的列表。
您正在測試,如果wordsDistributionList
(這顯然是一個地圖,而不是一個列表)中包含的關鍵word.toLowerCase()
但得到的關鍵值word
。 這很容易為空。
僅供參考,而不是
if(wordsDistributionList.containsKey(word.toLowerCase()) == true)
寫吧
if(wordsDistributionList.containsKey(word.toLowerCase()))
而不是
dbls.add(new Double(dbl));
寫吧
dbls.add(dbl);
后者稱為自動裝箱 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.