簡體   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