Traversing ArrayLists with Loops
Introduction: 7.3.0
- While, for, and for-each loops can all be used with ArrayLists
For Each Loop: 7.3.1
ArrayList<String> shoppingList = new ArrayList<String>();
shoppingList.add("Eggs");
shoppingList.add("Spam");
shoppingList.add(0, "Coffee");
for (String item : shoppingList) {
System.out.println(item);
}
- Do not use a for-each loop if you want to add or remove elements in the loop
- It doesn’t use an index, so it can’t keep track of conditional incrementing based on additions/removals
- Throws a
ConcurrentModificationException
- Throws a
- It doesn’t use an index, so it can’t keep track of conditional incrementing based on additions/removals
For and While Loops: 7.3.2 and 7.3.3
- You can use
while
orfor
to process list elements using an index- Index still starts at 0, like with arrays
- use
.get()
andset(index, val)
instead of[]
- If you try to
.get()
a value which isn’t in an array, you still get anArrayOutOfBoundsException
- Remember that removing items shifts all elements up from it to the left
- This also changes the last index
Summary: 7.3.6
- ArrayLists can be traversed with all the same types of loops as arrays
- Removing elements during a loop requires special techniques to avoid skipping elements
- This changes the indices of other elements
- Accessing an index outside of the range of elements will throw an
ArrayOutOfBoundsException
- Changing the size of an ArrayList during a for-each loop can result in a
ConcurrentModificationException
- tl;dr use a regular for loop if you’re adding/removing elements
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.