Skip to content Skip to sidebar Skip to footer

Add Buttons To Arraylist At The Specifed Index

I am trying to add a button to an ArrayList, but when I specify the index an error comes up saying the index is out of bounds. I initiate the array like this: ArrayList

Solution 1:

Check the documentation for ArrayList add method ..... it tells what could be the reason...

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(int, E)

Probably value of order is more than the size of the ArrayList. Print value of order before adding it to the list it will help...

Solution 2:

You can't add an element at a given index if the index is greater than the ArrayList's size. The documentation clearly states this I suppose.

Solution 3:

The .add(int index, E object) method will throw an IndexOutOfBoundsException when: index < 0 || index > size().

Check the value of your order variable before calling the method.

Solution 4:

If u already know what will be the final size of the array i advise you to set the capacity when u create the array Like this : "ArrayList buttons = new ArrayList (25);" being 25 the number of elements of your array, starting from 0 to index 24, to qvoid index out of bounds error i also advise u to populate your array,then u write buttons.add(index,element) at the specif index there is already an element what it will do is shift the existing element to the next position (if the index of the element was 0 ,after adding will be 1),instead u should try buttons.set(index,element) in this way pre existing element will be replaced with the one u wish to add

Post a Comment for "Add Buttons To Arraylist At The Specifed Index"