繁体   English   中英

如何在Java中的映射中存储链接到字符串键的ArrayList

[英]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>>();

如果由于从未初始化MapparseData )而得到NullPointerException的原因。 您需要像这样初始化parseData:

Map<String, List<String> > parsedData = new HashMap<String, ArrayList<String>>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM