1

I have to create an ArrayList of ArrayList i.e.

ArrayList<ArrayList<Integer>> l=new ArrayList<ArrayList<Integer>>();

I will be receiving the values for the inner list at random i.e. sometimes I might get the value for the first inner list, sometimes for the second. So, I have to do something like, l.get(x).add(y); But since initially all the outer list variables point at null this would give me an error. I somehow need to initialize all the outer list as an empty list [] and not null to which I can get a valid reference.

Any idea on how to get around this problem?

9
  • What if you initialize then with 0? Commented Apr 19, 2017 at 0:45
  • 1
    suppose this post has a good solution for this issue. Commented Apr 19, 2017 at 0:45
  • I don't think I can initialise it with 0 because I dont know the size of the inner list. Commented Apr 19, 2017 at 0:47
  • why not just use int instead? this way you have a default 0 value Commented Apr 19, 2017 at 0:49
  • That's just the scenario. I dont know the size of the inner lists. I will receive the values at random and accordingly need to add them to respective inner list. Commented Apr 19, 2017 at 0:50

1 Answer 1

2

You could create your own list that extends ArrayList overriding the add() type functions and when the add() or similar function is called, ensures that the Array is at least as long as the current index + 1 before inserting the child Array.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.