0

I have a data structure of the following form:

HashMap<Integer, ArrayList<ArrayList<Integer>>> map = new HashMap<Integer, ArrayList<ArrayList<Integer>>>();

// I am trying to add a new list inside the map's value if the value is already present in the hash.

while(//some condition){
  if(!map.containsKey(//some value)){
    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
    map.put(//some value, list);
    ArrayList<Integer> currentList = new ArrayList<Integer>();
    currentList.add(1); currentList.add(2);
    map.get(//some value).set(map.get(//some value).size(), currentList);
  }
  else{
    ArrayList<Integer> currentList = new ArrayList<Integer>();
    currentList.add(1); currentList.add(2);
    map.get(//some value).set(map.get(//some value).size(), currentList);
  }
}

But this throws up an error saying IndexOutOfBoundsException at Index: 0 and Size: 0

Spider Man
  • 415
  • 4
  • 10
  • 26
  • What line is the exception? – Eli Sadoff Nov 12 '16 at 15:03
  • 1
    To add something to an arraylist, you use the add() method. Not the set() method. set() replaces an element by something else. But your list has no element. Read the javadoc. – JB Nizet Nov 12 '16 at 15:05
  • Btw: bad idea to replace code with "some value", since one of them is the culprit here. Most likely this `map.get(//some value).set(map.get(//some value).size(), currentList)`, because using `size()` is obviously a **very bad** idea for adding a new item (see JB Nizets comment above). – Tom Nov 12 '16 at 15:05
  • Thanks a lot @JBNizet, it explains clearly why I can't do this. – Spider Man Nov 12 '16 at 16:36
  • Thanks @Tom for the suggestion. – Spider Man Nov 12 '16 at 16:36

0 Answers0