[英]How to store an ArrayList linked to String keys in a Map in Java
I am reading in a data file which consists of three String data types per line. 我正在读取一个数据文件,该文件每行包含三种String数据类型。 Each line is read individually and stored to an ArrayList called temp. 每行都单独读取,并存储到称为temp的ArrayList中。 I want to take the 3rd element of temp and use it as a key in a Map which Maps the key to the contents of Temp and do this for each line. 我想使用temp的第三个元素,并将其用作Map中的键,该Map将键映射到Temp的内容,并针对每一行执行此操作。 I have the following code, which compiles but when run gives me a null error the assignment to parsedData. 我有以下代码,可以编译,但运行时给我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());
}
You haven't initialized parsedData to anything. 您尚未将parsedData初始化为任何东西。 It has null
reference. 它具有null
引用。 When you try to do put
on null reference you will get NullPointerException
. 当你尝试做put
对空引用您将得到NullPointerException
。
Map<String,ArrayList<String> > parsedData= new HashMap<String, ArrayList<String>>();
The reason you are getting NullPointerException
if because you never initialize your Map
( parseData ). 如果由于从未初始化Map
( parseData )而得到NullPointerException
的原因。 You need to initialize your parseData like this: 您需要像这样初始化parseData:
Map<String, List<String> > parsedData = new HashMap<String, ArrayList<String>>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.