Kurlicue Kurlicue - 1 year ago 69
Android Question

add a variable into an array in a specific position

I'm trying to add a string into my array in the 3rd position because I need to do so for a loop I'm executing after it.

ArrayList<String> namesArray = new ArrayList<>();
namesArray.add(3, mString);

It gives an out of bonds expection, is this not possible to do?

java.lang.IndexOutOfBoundsException: Invalid index 3, size is 0

ajb ajb
Answer Source

When you say

arrayList.add(n, value);

the result is that after the add, arrayList.get(n) will have that value. You're trying to arrange things so that arrayList.get(3) will be mString. However, an ArrayList must be a list of consecutive elements; it can't be a "sparse array". That is, for arrayList.get(3) to exist, arrayList.get(0), arrayList.get(1), and arrayList.get(2) must also exist.

I don't know what you want those values to be (maybe null?), but you do have to set them. Java's ArrayList doesn't have an add method that automatically fills in the gap with a default value. You can add 3 nulls to the array like this:

arrayList.addAll(Arrays.asList(new String[3]));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download