- 7.3: Traversing Arrays
- Quick Quiz
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:
regular while loops are syntaxed as follows:
removing items within an array -> each item moves up a slot
Traversing backwards:
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:
Using a for each loop for same objective as before:
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