![](/img/trans.png)
[英]How to work with Java map with<String, Arraylist<Integer>>
[英]How to store an ArrayList linked to String keys in a Map in Java
我正在讀取一個數據文件,該文件每行包含三種String數據類型。 每行都單獨讀取,並存儲到稱為temp的ArrayList中。 我想使用temp的第三個元素,並將其用作Map中的鍵,該Map將鍵映射到Temp的內容,並針對每一行執行此操作。 我有以下代碼,可以編譯,但運行時給我parsedData的賦值為空錯誤。
Map<String,ArrayList<String> > parsedData;
int pos;
String line;
StringBuilder buffer = new StringBuilder();
ArrayList<String> temp;// = new ArrayList<String>();
try {
temp = new ArrayList<String>();
while ((line = inBufR.readLine()) != null){
buffer.append(line);
while (buffer.length() != 0){
pos = buffer.indexOf(delim);
if (pos != -1){ //Cases where delim is found
temp.add( buffer.substring(0,pos).trim() );
buffer.delete(0,pos+delim.length()); //Cannibalizing the string
while ( (buffer.indexOf(delim)) == 0){
buffer.delete(0,delim.length());
}
} else { //Cases where delim is not found
temp.add( buffer.substring(0,buffer.length()).trim() );
buffer.delete(0,buffer.length()); //clearing the string
} // else
}//while (buffer.length() !=0
parsedData.put(temp.get(keyCol) , temp);
temp.clear();
}//while ((buffer = inBufR.readLine()) !=null)
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
}
您尚未將parsedData初始化為任何東西。 它具有null
引用。 當你嘗試做put
對空引用您將得到NullPointerException
。
Map<String,ArrayList<String> > parsedData= new HashMap<String, ArrayList<String>>();
如果由於從未初始化Map
( parseData )而得到NullPointerException
的原因。 您需要像這樣初始化parseData:
Map<String, List<String> > parsedData = new HashMap<String, ArrayList<String>>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.