Fiveable
Fiveable
pep
Fiveable
Fiveable

or

Log in

Find what you need to study


Light

7.3 Traversing ArrayLists

3 min readdecember 30, 2022

Athena_Codes

Athena_Codes

Milo Chang

Milo Chang

Athena_Codes

Athena_Codes

Milo Chang

Milo Chang

Traversing ArrayLists

Now that we have made our , it is time to traverse the ! To traverse an , we can use the same two methods that we use to traverse regular arrays: using the regular and the .

There are only two differences in the implementation.

  • Instead of using bracket notation, we use get().

  • We use size() for the 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 , you'll get a .

Here is an example of the implementation:

public static void forTraversal(<E> list) { for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } }

The code is basically unchanged. Here is an example of the implementation:

public static void enhancedForTraversal(<E> list) { for (E element: list) { System.out.println(element); } }

As with arrays, we can only change the items in an using set(), and not by changing the variable, as Java is a pass-by-value language. However, as before, we can change instance variables of objects inside ArrayLists using an .

Traversing while Removing Elements

Sometimes we want to remove elements while traversing the . This can only be done with the regular . Changing the size of an (either by adding or removing elements) while using an will result in a .

When deleting an element at an index i, remember that the element that used to be at index i+1 (the next element) is now at index i. This will require us to do an i-- before the loop incrementation to avoid skipping an element.

The size() in the loop condition will automatically change as you add or remove items, so we don't need to worry about it not being accurate or the method crashing. Here is a method that removes all even numbers from an like integerList above:

/** Removes all even numbers */ public static <Integer> removeEvens(<Integer> list) { for (int i = 0; i < list.size(); i++) { if (list.get(i) % 2 == 0) { list.remove(i); i--; } } }

Traversing while Adding Elements

Other times, we may want to add elements to an during traversal. However, this brings up its own problem. Let's take a look:

  1. Let's have a method that inserts a 1 at index i, if the element at i is equal to 4.

  2. At some index i, the element is 4, so 1 is now added at index i.

  3. That 4 is now at index i+1.

  4. i is incremented, so the current index being checked is i+1.

  5. At index i+1, the element is 4, so steps 2-4 are repeated, causing an infinite loop!

To avoid an infinite loop, we increment i before the loop incrementation so that i++ occurs twice and the loop checks the actual next item. Let's see this by duplicating all odd numbers in an like integerList:

/** Duplicates all odd numbers */ public static <Integer> duplicateOdds(<Integer> list) { for (int i = 0; i < list.size(); i++) { if (list.get(i) % 2 == 1) { list.add(i, list.get(i)); i++; } } }

Key Terms to Review (10)

add()

: The add() method is used to insert an element into a data structure, such as a list or set.

ArrayList

: ArrayList is a dynamic data structure that allows you to store and manipulate collections of objects. Unlike arrays, ArrayLists can grow or shrink dynamically as needed.

ConcurrentModificationException

: A ConcurrentModificationException occurs when a collection is modified while being iterated over using an iterator or enhanced for loop.

Enhanced For Loop

: An enhanced for loop (also known as a foreach loop) is a simplified way to iterate over elements in an array or collection. It automatically handles indexing and provides an easy way to access each element without explicitly using indices.

For Loop

: A for loop is a control flow statement that allows you to repeatedly execute a block of code for a specified number of times or until certain conditions are met.

get()

: The get() method is used to retrieve the value of an element at a specific index in a list or array.

IndexOutOfBoundsException

: IndexOutOfBoundsException is an exception that occurs when trying to access an invalid index position within an array or collection.

remove()

: The remove() method removes an element from a collection, if it exists, and returns true. If the element doesn't exist, it returns false.

set()

: A set is a collection of unique elements with no specific order. It does not allow duplicate values.

size()

: The size() method is used to determine the total number of elements present in a collection, such as a list or array.

7.3 Traversing ArrayLists

3 min readdecember 30, 2022

Athena_Codes

Athena_Codes

Milo Chang

Milo Chang

Athena_Codes

Athena_Codes

Milo Chang

Milo Chang

Traversing ArrayLists

Now that we have made our , it is time to traverse the ! To traverse an , we can use the same two methods that we use to traverse regular arrays: using the regular and the .

There are only two differences in the implementation.

  • Instead of using bracket notation, we use get().

  • We use size() for the 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 , you'll get a .

Here is an example of the implementation:

public static void forTraversal(<E> list) { for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } }

The code is basically unchanged. Here is an example of the implementation:

public static void enhancedForTraversal(<E> list) { for (E element: list) { System.out.println(element); } }

As with arrays, we can only change the items in an using set(), and not by changing the variable, as Java is a pass-by-value language. However, as before, we can change instance variables of objects inside ArrayLists using an .

Traversing while Removing Elements

Sometimes we want to remove elements while traversing the . This can only be done with the regular . Changing the size of an (either by adding or removing elements) while using an will result in a .

When deleting an element at an index i, remember that the element that used to be at index i+1 (the next element) is now at index i. This will require us to do an i-- before the loop incrementation to avoid skipping an element.

The size() in the loop condition will automatically change as you add or remove items, so we don't need to worry about it not being accurate or the method crashing. Here is a method that removes all even numbers from an like integerList above:

/** Removes all even numbers */ public static <Integer> removeEvens(<Integer> list) { for (int i = 0; i < list.size(); i++) { if (list.get(i) % 2 == 0) { list.remove(i); i--; } } }

Traversing while Adding Elements

Other times, we may want to add elements to an during traversal. However, this brings up its own problem. Let's take a look:

  1. Let's have a method that inserts a 1 at index i, if the element at i is equal to 4.

  2. At some index i, the element is 4, so 1 is now added at index i.

  3. That 4 is now at index i+1.

  4. i is incremented, so the current index being checked is i+1.

  5. At index i+1, the element is 4, so steps 2-4 are repeated, causing an infinite loop!

To avoid an infinite loop, we increment i before the loop incrementation so that i++ occurs twice and the loop checks the actual next item. Let's see this by duplicating all odd numbers in an like integerList:

/** Duplicates all odd numbers */ public static <Integer> duplicateOdds(<Integer> list) { for (int i = 0; i < list.size(); i++) { if (list.get(i) % 2 == 1) { list.add(i, list.get(i)); i++; } } }

Key Terms to Review (10)

add()

: The add() method is used to insert an element into a data structure, such as a list or set.

ArrayList

: ArrayList is a dynamic data structure that allows you to store and manipulate collections of objects. Unlike arrays, ArrayLists can grow or shrink dynamically as needed.

ConcurrentModificationException

: A ConcurrentModificationException occurs when a collection is modified while being iterated over using an iterator or enhanced for loop.

Enhanced For Loop

: An enhanced for loop (also known as a foreach loop) is a simplified way to iterate over elements in an array or collection. It automatically handles indexing and provides an easy way to access each element without explicitly using indices.

For Loop

: A for loop is a control flow statement that allows you to repeatedly execute a block of code for a specified number of times or until certain conditions are met.

get()

: The get() method is used to retrieve the value of an element at a specific index in a list or array.

IndexOutOfBoundsException

: IndexOutOfBoundsException is an exception that occurs when trying to access an invalid index position within an array or collection.

remove()

: The remove() method removes an element from a collection, if it exists, and returns true. If the element doesn't exist, it returns false.

set()

: A set is a collection of unique elements with no specific order. It does not allow duplicate values.

size()

: The size() method is used to determine the total number of elements present in a collection, such as a list or array.


© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.


© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.