While loops, for loops, and enhanced for each loops can all be used to traverse an ArrayList just like an array.
You can also use a while
or for
loop to process list elements using the index. The ArrayList index starts at 0 just like arrays, but instead of using the square brackets [] to access elements, you use get(index)
to get the value at the index and set(index,value)
to set the element at an index to a new value. If you try to use an index that is outside of the range of 0 to the number of elements − 1 in an ArrayList, your code will throw an ArrayIndexOutOfBoundsException, just like in arrays.
The following code will throw an ArrayIndexOutOfBoundsException. Can you fix it?
The example below demonstrates a while loop and an object-oriented approach where the list is a field of the current object and you use an object method rather than a class (static) method to loop through the list.
What does the following code do? Guess what it does before running it. Can you change the code so that it only removes the first name it finds in the list that matches?
Be careful when you remove items from a list as you loop through it. Remember that removing an item from a list will shift the remaining items to the left. Notice that the method above only increments the current index if an item was not removed from the list. If you increment the index in all cases you will miss checking some of the elements since the rest of the items shift left when you remove one.
Do not use the enhanced for each loop if you want to add or remove elements when traversing a list because it will throw a ConcurrentModificationException error. Since for each loops do not use an index, you cannot do this special case of incrementing only if it is changed. So if you are going to add or remove items or you need the index, use a regular for loop or a while loop.