I was writing something that needs an arrayList of size n, so I did the following:
List<Set<Integer>> list = new ArrayList<Set<Integer>(n);
And when I was trying to access an element of the list e.g.
list.get(someValue that is <n)
I got arrayList out of bound exception, so I guess putting a n there doesn't really help you initialize the list, but just pre-allocate the space.
Is there a way to do the initialization after which there are actually null or objects in each slot?
I end up using a for loop and adding n empty set and then index into the list.
Is there a better way TO INITIALIZE AN ARRAYLIST IF THE SIZE IS KNOWN IN ADVANCE?
Please know what I'm asking before saying this is a duplicate.
Hope my question is clear.
Thanks in advance.
Some of you think what I tried to do is meaningless. This happens when I tried to solve a bucket sort related problem where the index of the set I tried to access in the array is known. So for example, I want to add some elements to the set at position 1, 3, 2, 4... then it would be convenient if I can just get the set at position 1, 3, 2, 4...