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

For and While Loops: 7.3.2 and 7.3.3

  • You can use while or for to process list elements using an index
    • Index still starts at 0, like with arrays
    • use .get() and set(index, val) instead of []
    • If you try to .get() a value which isn’t in an array, you still get an ArrayOutOfBoundsException
  • 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