Question

I am trying to add a multiple hashmap objects to the list. First one is added OK. But on the next round it crashes with exception error "5". I do create a new hshmap object for each round, but it still crashes.

HashMap<String, Object> data;
ArrayList<HashMap<String, Object>> dataList = new ArrayList<HashMap<String, Object>>();

for(int i=0;i<iCount;i++)
    {
        arrRow = resSearchItems.get(i).split("\\^"); 

        {
            data = new HashMap<String, Object>();           

            data.put("ResNumber", arrRow[0]);
            data.put("MeetingType#", arrRow[1]);
            data.put("Topic", arrRow[2]);
            data.put("MeetingDate", arrRow[3]);
            data.put("Motion", arrRow[4]);
            data.put("Votes", arrRow[5]);

            dataList.add(data);

        }                       
    }

Thank you

No correct solution

OTHER TIPS

You should check arrRow.length -1 to be maximum index you want to access the array. If this value is less than 5 then you'll get ArrayIndexOutOfBoundsException.

resSearchItems.get(i) where i = 1, might return null, we cannot guess. Also, if arrRow doesn't contain 6 or more elements, then a java.lang.ArrayIndexOutOfBoundsException will be thrown.

Two thoughts:

  1. Where does iCount come from?
  2. Try replacing the method call to retrieve data with:

    arrRow = "one^two^three^four^five^six".split("\\\\^");

and see if your code still crashes. This compiles and runs fine for me:

import java.util.HashMap;
import java.util.ArrayList;

public class HashmapTest {
  public static void main(String args[]) {
    HashMap<String, Object> data;
    ArrayList<HashMap<String, Object>> dataList = new ArrayList<HashMap<String, Object>>();
    String[] arrRow;
    int iCount = 4;

    for(int i=0;i<iCount;i++) {
      arrRow = "one^two^three^four^five^six".split("\\^"); 
      data = new HashMap<String, Object>();           

      data.put("ResNumber", arrRow[0]);
      data.put("MeetingType#", arrRow[1]);
      data.put("Topic", arrRow[2]);
      data.put("MeetingDate", arrRow[3]);
      data.put("Motion", arrRow[4]);
      data.put("Votes", arrRow[5]);

      dataList.add(data);

    }                       
    System.out.println("hashmap count:" + dataList.size());
  }
}

Is this some kind of scraped data? If each of the resSearchItems Strings does not contain 6 items you might want to try something like:

 HashMap<String, Object> data;
 ArrayList<HashMap<String, Object>> dataList = new ArrayList<HashMap<String, Object>>();
 String[] hashKeys = {"ResNumber","MeetingType#","Topic","MeetingDate","Motion","Votes"};

 for(int i=0;i<iCount;i++) {
   arrRow = resSearchItems.get(i).split("\\^");  
   data = new HashMap<String, Object>();           

   for(int j=0;j<arrRow.length && j<hashKeys.length;j++) 
      data.put(hashKeys[j], arrRow[j]);

   dataList.add(data);
 }         
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top