Title: IndexOutOfBoundsException even though the elements exist in the arraylist
Tags: java;arraylist;linked-list
Question: I have 10001 elements in the ArrayList when I am trying to remove them one by one, I get IndexOutOfBoundsException exception midway i.e. after 5000 elements. Don't really know why.
public static void main(String[] args) {
List<Integer&gt; numberArrayList = new ArrayList<&gt;();
List<Integer&gt; numberLinkedList = new LinkedList<&gt;();
long start, end;
start = System.currentTimeMillis();
for (int i = 0; i < 10_001; i++) {
numberArrayList.add(i);
end = System.currentTimeMillis();
System.out.println("Time taken to insert 10_001 elements in ArrayList: " + (end - start));
start = System.currentTimeMillis();
for (int i = 0; i < 10_001; i++) {
numberLinkedList.add(i);
end = System.currentTimeMillis();
System.out.println("Time taken to insert 10_001 elements in LinkedList: " + (end - start));
/* **************************************************************/
start = System.currentTimeMillis();
for (int i = 0; i < 10_001; i++) {
numberArrayList.remove(i);
end = System.currentTimeMillis();
System.out.println("Time taken to remove 10_001 elements from the front in ArrayList: " + (end - start));
start = System.currentTimeMillis();
for (int i = 0; i < 10_001; i++) {
numberLinkedList.remove(i);
end = System.currentTimeMillis();
System.out.println("Time taken to remove 10_001 elements from the front in LinkedList: " + (end - start));
The above program results in
Time taken to insert 100_001 elements in ArrayList: 2
Time taken to insert 100_001 elements in LinkedList: 1
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5001, Size: robertjones@example.net(ArrayList.java:657)
at java.util.ArrayList.remove(ArrayList.java:496)
at collections_jnit.list.ArrayList_vs_LinkedList.main(ArrayList_vs_LinkedList.java:34)
Comment: If you need remove all items ,just use `clear()`

Comment: `remove()` shifts the subsequent remaining elements down one index. So, after you've removed 5000 elements, the last index is 5000.

Comment: Because you are removing elements as you iterate it. Halfway through you have removed half of the elements and bam, now out of bounds.

Here is the accepted answer: Once you remove 5000 elements mean 10001-5000 = 5001 so considering the indexing from 0 so now range of index is 0 to 5000 hence the exception with 5001.
Solution : if you want to remove items from list while traversing then I recommend to use Iterators
Iterator<Integer&gt; itr = numberArrayList.iterator();
while (itr.hasNext()) {
itr.remove();
Comment for this answer: @MenaiAlaEddine in this case, OP is doing some bench marking tests(so I didn't suggest ), although `clear` almost does the same thing using loops though it is concise and time effective
Comment for this answer: Why we need to iterate each item if we will clear all List ? I think `List.clear()` is safety.
Comment for this answer: I have not a deep experience ,but i thought we use Iterator and removeIf () ..etc ,if we need to remove some items , i mean when we have a condition.

Here is another answer: You can change it to a while loop:
while (numberLinkedList.size() &gt; 0) {
numberLinkedList.remove(0);
With the for loop, you are removing the object at i which is increasing every iteration and thus you end up only removing half the items.

Here is another answer: As already answered, why you are getting IndexOutOfBoundException, so I am going to add, how can you safely remove all the elements. There are two ways of doing this:
ArrayList.clear()
ArrayList.removeAll()
Both of the methods are inherited from List into ArrayList. 1 is faster than 2.

Here is another answer: numberLinkedList.clear();
or if you want to iterate, Use Java 8+ :)
numberLinkedList.removeIf(i -> true);

Here is another answer: Lists are not Arrays.
If you add an element to a List with size N the list size will be increased, that means you can access the element N + 1. If you remove any element, you cannot access the element N + 1, this element will be in the position N.
Arrays has fixed positions and fixed size.
Please, look the documentation:
Collections

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 5, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2018:00:03/28/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><arraylist><linked-list>', 'Title': 'IndexOutOfBoundsException even though the elements exist in the arraylist', 'ViewCount': 801, 'id': 49541358, 'user_AboutMe': None, 'user_AccountId': 7835925.0, 'user_DisplayName': 'Pritam Bohra', 'user_Reputation': 3438.0, 'user_Views': 275.0, 'user_id': 5924007.0}}