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:
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"