I am trying to increase the size of an ArrayList inside an ArrayList whenever a new value is added but I'm not sure on the correct way to do so. This is what I have right now:
public ArrayList<ArrayList<Integer>> outerList;
public int addValue(int value) {
int a = 0;
ArrayList<Integer> innerList = new ArrayList<Integer>();
if (noValue(value) == true) { // noValue checks if the value exists at a position in outerList and returns true if it's empty
innerList.add(value); // innerList has now size 1
outerList.add(innerList);
}
else {
a += 1;
innerList.add(value);
outerList.add(innerList);
}
return a;
}
But based on my tests, the size of innerList remains 1.
ArrayListfor inner list. Yourelseblock should add to the existing list instead of using a newly created one.Map<Integer, List<Integer>>or possibly aMap<Integer, Integer>(and only store how often you added the value) and use theMap#computemethods to simplify the code. E.g.addValue(int value)=map.computeIfAbsent(value, i -> new ArrayList<>()).add(value)with the map of lists.if (noValue(value))is sufficient.