2

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.

4
  • 2
    You are just adding 1 item to it, so one would expect the size to be 1. Commented Oct 8, 2018 at 15:38
  • 1
    You're always using a new ArrayList for inner list. Your else block should add to the existing list instead of using a newly created one. Commented Oct 8, 2018 at 15:39
  • looks like you could use a Map<Integer, List<Integer>> or possibly a Map<Integer, Integer> (and only store how often you added the value) and use the Map#compute methods to simplify the code. E.g. addValue(int value) = map.computeIfAbsent(value, i -> new ArrayList<>()).add(value) with the map of lists. Commented Oct 8, 2018 at 15:47
  • BTW: if (noValue(value)) is sufficient. Commented Oct 8, 2018 at 16:17

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

You never get anything from outerList, all instances of innerList will always be newly created and then get one new entry added. Then that innerList is added to outerList and never touched again.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.