ArrayList: a standard Java class
for keeping track of lists of things
add method. The list grows as
needed. You can determine the number of items in a list by invoking
the size method.get method, for example), the compiler will
automatically unwrap the primitive from its wrapper (known as
auto-unboxing).Constructing an ArrayList -- note the type of the list elements given in angle brackets:
ArrayList<Integer> numberList = new
ArrayList<Integer>();ArrayList<Fish> listOfFish = new
ArrayList<Fish>();Adding elements to the end of a list:
numberList.add(new Integer(42));numberList.add(new Integer("42"));numberList.add(42);
// taking advantage of auto-boxinglistOfFish.add(new Fish("trout"));Determining how many items are in a list: theArrayList.size()
System.out.println(numberList.size());
// prints 3 (added 3 copies of Integer 42 above)System.out.println(listOfFish.size());
// prints 1 (added 1 Fish to list above)Accessing elements in an ArrayList: theArrayList.get(indexOfElement)
theArrayList.set(indexOfElement, value)
System.out.println(numberList.get(0)); |
// accesses first element in list | |
System.out.println(numberList.get(numberList.size()-1)); |
// accesses last element in list | |
int value = numberList.get(index); |
// taking advantage of auto-unboxing | |
listOfFish.get(fishNum).moveForward(); |
We often use loops to step through an ArrayList.
// Reset every number in the list to 0.
for (int index=0; index < numberList.size(); index++)numberList.set(index,
0);// Print every number in the list.
for (int index=0; index < numberList.size(); index++)System.out.println(numberList.get(index);// Ask every fish in the list to move forward.
for (int index=0; index < listOfFish.size(); index++)listOfFish(index).moveForward();If we are not changing which items are in the ArrayList, we can use the special for each style of loop to step through the list.
// Print every number in the list.
for ( Integer value : numberList )System.out.println(value);// Ask every fish in the list to move forward.
for ( Fish f : listOfFish )f.moveForward();A subset of handy ArrayList methods:
size() | returns number of elements in list | |
isEmpty() | returns true if the list is empty; false otherwise | |
add(E element) | adds given element to end of list | |
add(int index, E element) | adds given element at specified index list, shifting later elements | |
get(int index) | returns element at specified index | |
set(int index, E element) | replaces the element currently at the specified index with the given element | |
remove(E element) | finds given element in list and removes it (first occurrence) | |
remove(int index) | removes element at specified index list, shifting later elements |