0

我正在读取一个数据文件,该文件每行包含三个字符串数据类型。每行单独读取并存储到名为 temp 的 ArrayList 中。我想获取 temp 的第三个元素并将其用作 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()); 
    }
4

2 回答 2

0

您尚未将 parsedData 初始化为任何内容。它有null参考。当您尝试put对空引用执行操作时,您将得到NullPointerException.

Map<String,ArrayList<String> > parsedData= new HashMap<String, ArrayList<String>>();
于 2012-10-23T19:17:47.087 回答
0

你得到的原因是NullPointerException因为你从未初始化你的MapparseData)。您需要像这样初始化 parseData:

Map<String, List<String> > parsedData = new HashMap<String, ArrayList<String>>();
于 2012-10-23T19:18:38.790 回答