I am trying to do something like:
ArrayList<String> al = new ArrayList(15);
al.add(5, "test");
my case with vector but it doesnt matter. I am missing something trivial.
However I get index out of bound exception.
Method api description:
“Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). ” – so?
My situation is that I get UDP packets and try to place their data them into structure according to header sequence number.
Update: same happens with .set
For beginners the constructor of ArrayList is confusing.
Putting
is basically just an optimization of your program upfront. The class ArrayList is basically just a wrapper around a native Java array. In this example the actual internal array will be created with 15 elements. When you put more than that, the ArrayList class just creates a bigger array and copies over the contents from the original array. Putting an initial capacity does not make sense very often. I only use it when I know from the beginning that I will story a huge number of elements in the ArrayList (say one million).
I know, this behavior is very confusing, especially if you are coming from a language like PHP, where you can just do:
Basically the
add(index, element)method just works if you have an ArrayList that contains more than index elements, squeezing the new element in after index-1.For the solution:
If you know that you will be receiving 15 elements max, it is perfectly ok to use an ordinary array like so:
If you don’t know the number of elements I would store them in a List and sort that list after all packages have been received.