I am trying to remove an object from an ArrayList, My code is
ArrayList myArrayList=new ArrayList();
for(int index=0;index<20;index++){
myArrayList.add(index);
}
for(int removeIndex=0;removeIndex<=mArrayList;removeIndex++){
myArrayList.remove(removeIndex);
}
It is giving a java.lang.IndexOutOfBoundsException. How do I remove a number of objects from ArrayList?.
Of course, as soon as you remove the 0th item, the last item is now 18th, because the items are reindexed.
You can use several tricks, for example, remove starting from the end. Or remove the 0th item until the array is empty (or until you removed some predefined number of items).
Code:
or
If you want to remove all the items, you can consider using
clear()as well.If you want to remove several positions from a list, you can try the following: