Issue
I am using the list.add(index, element)
function to insert elements into an ArrayList, where the index is not in order.
For eg,
first i call list.add(5, element5)
and then list.add(3, element3)
I am getting the exception java.lang.IndexOutOfBoundsException: Invalid index 5, size is 0
exception.
Please tell where I am doing wrong and how can I fix this.
Solution
You can only use indexes that are existing or one larger than the last existing. Otherwise you would have some spots with no element in it. If you need a ficxed length to store elements on a specified position, try to fill the List before with empty entries or use an array:
MyElement[] myArray = new MyElement[theLengthOfMyArray];
myArray[5] = elementXY;
Or fill a List with null elements (shown here):
List<MyElement> myList = new ArrayList<>();
for (int i = 0; i < theTargetLengthOfMyList; i++) {
myList.add(null);
}
myList.set(5, elementXY);
Answered By - Japhei
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.