Traversing ArrayLists

Sophie Anderson
5 min read
Listen to this study note
Study Guide Overview
This guide covers traversing ArrayLists using for loops and enhanced for loops. It explains the differences between traversing ArrayLists and arrays, including using get()
and size()
. It also discusses removing and adding elements during traversal, highlighting how to avoid ConcurrentModificationException
and infinite loops using index adjustments (i--
, i++
). Finally, it touches upon pass-by-value in Java and its implications for modifying ArrayList elements.
#Traversing ArrayLists
Now that we have made our ArrayList, it is time to traverse the ArrayList! To traverse an ArrayList, we can use the same two methods that we use to traverse regular arrays: using the regular for loop and the enhanced for loop.
There are only two differences in the for loop implementation.
- Instead of using bracket notation, we use get()).
- We use size()) for the ArrayList instead of the length variable. Like with regular array traversals using for loops, if you try to access an index outside of the range of the ArrayList, you'll get a IndexOutOfBoundsException.
Here is an example of the for loop implementation:
public static void forTraversal(ArrayList
The enhanced for loop code i...

How are we doing?
Give us your feedback and let us know how we can improve