7.3 Traversing ArrayLists
Enduring Understanding
To manage large amounts of data or complex relationships in data, programmers write code that groups the data together into a single data structure without creating individual variables for each value.
Learning Objective
For ArrayList objects:
a. Traverse using a for or while loop
b. Traverse using an enhanced for loop
Essential Knowledge
Iteration statements can be used to access all the elements in an ArrayList. This is called traversing the ArrayList.
Deleting elements during a traversal of an ArrayList requires using special techniques to avoid skipping elements.
Since the indices for an ArrayList start at 0 and end at the number of elements − 1, accessing an index value outside of this range will result in an ArrayIndexOutOfBoundsException being thrown.
Changing the size of an ArrayList while traversing it using an enhanced for loop can result in a ConcurrentModificationException being thrown. Therefore, when using an enhanced for loop to traverse an ArrayList, you should not add or remove elements.
Last updated
Was this helpful?