Increasing size of ArrayList in ArrayList in Java

rndm :

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.

GBlodgett :

But based on my tests, the size of innerList remains 1.

This is because in your addValue() method you create a new innerList and add it to the list. Thus your outer ArrayList will consist of a lot of ArrayList's with only one object in them.

To change this you should use the get() method to get the inner ArrayList and then add the item to it. Something like:

outerList.get(index).add(value);

Where index is the index of the inner list you want to add the value to

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112016&siteId=1