zuai-logo
zuai-logo
  1. AP Computer Science A
FlashcardFlashcardStudy GuideStudy Guide
Question BankQuestion Bank

Traversing ArrayLists

Sophie Anderson

Sophie Anderson

5 min read

Next Topic - Developing Algorithms Using ArrayLists

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 list) { for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } }

The enhanced for loop code i...

Feedback stars icon

How are we doing?

Give us your feedback and let us know how we can improve

Previous Topic - ArrayList MethodsNext Topic - Developing Algorithms Using ArrayLists

Question 1 of 8

What is the correct way to access an element at index i in an ArrayList called list using a regular for loop? 🤔

list[i]

list.get(i)

list.element(i)

list.indexOf(i)