Skip to the content.

Unit 7 ArrayList P3

A Unit of documents that overview Array Lists in Java

AP CSA

7.3: Traversing Arrays

functions to traverse an array

  • variable.get(i): retreives #i value.
  • variable.remove(i): removes #i value from a list.
  • variable.size(): retreives length of the array
  • swapConsecutive(ArrayList myList): swaps items in an ArrayList

Possible strategies to iterate through a for loop:

Conditions

regular while loops are syntaxed as follows:

image

removing items within an array -> each item moves up a slot

image

Traversing backwards:

image

traversing using and enhanced for loop known as for-each goes from first to last order in an ArrayList easier to setup than for loop structure consists of:

image

Using a for each loop for same objective as before:

image

Notes:

  • Adding items to a for each loop will result in an exception
  • modifying or adding items will not effect the Arraylist. Results in ConcurrentModificationException
  • attempting to access an item outside of the Array bounds results in: ArrayIndexOutOfBoundsException

use this to make sure you can traverse ArrayLists

import java.util.ArrayList

Quick Quiz

1. Which of the following are methods to interact with arrays?





2. What happens when you run a command requesting the item arr[-1]?