import java.util.ArrayList;
public class WTFAMIDOINGWRONG
{
public static void main(String[] args)
{
ArrayList<Integer> intsAR = new ArrayList<Integer>(5);
intsAR.add(3, 1);
}
}
So, I've been fooling around with this for about an hour and I haven't the slightest Idea what I could be doing wrong. No matter what I do, it's convinced the arraylist has no size and everything is therefore out of bounds. If anyone could tell me what I'm doing wrong I'd really appreciate it.
3 Answers 3
An ArrayList is backed by an array, so when you specify the initial capacity, you are specifying how large of an array to allocate. This is important because it specifies how much memory the ArrayList will occupy sequentially.
However, the size of the ArrayList specifies how many items are actually in the list. Once the list reaches a certain size (relative to the capacity of the backing array), the backing array will be reallocated to take up additional space.
If you wanted to create an ArrayList of 10 items, all with 0, you would do:
List<Integer> list = new ArrayList<Integer>();
for ( int i = 0; i < 10; i++ ) {
list.add(0);
}
Now you could insert an item at position 3 (or somewhere in the middle) if you wanted to.
3 Comments
List<Integer> list = new ArrayList<Integer>(Collections.nCopies(10, 0)); or List<Integer> list = new ArrayList<Integer>(); list.addAll(Collections.nCopies(10, 0));.Because the size of your list is ZERO. Yes, you are actually constructing it by specifying the initialCapacity, but that doesn't mean size. Are you getting my point? You can say that taht will just reserve the space for future.
BTW, size() documentation clearly states that, it is the number of elements in the list. Now, I hope you know what is happening.
Comments
You cannot insert into an empty list in position 3 - what would be the first 2 elements then? With empty list only intsAR.add(0, 1); will work
instAR.add(1);? It will not require any index.int[], instead.