简体   繁体   中英

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. Each line is read individually and stored to an ArrayList called temp. 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. I have the following code, which compiles but when run gives me a null error the assignment to 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. It has null reference. When you try to do put on null reference you will get 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 ). You need to initialize your parseData like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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