An ArrayList is a class in Java that stores a list of items.
It is like an array, but it is more flexible because it can grow or shrink as needed.
ArrayList<String> names = new ArrayList<String>();
This creates an ArrayList that stores String values.
To use an ArrayList, you must import it:
import java.util.ArrayList;
The add() method puts a new item into the ArrayList.
list.add(value);
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
The items are added to the end of the list.
[Apple, Banana, Orange]
Important idea:
add() increases the size of the list by 1.The remove() method deletes an item from the ArrayList.
list.remove(index);
fruits.remove(1);
This removes the item at index 1.
Before:
[Apple, Banana, Orange]
After:
[Apple, Orange]
Important idea:
ArrayList indexes start at 0.The set() method changes an existing item in the list.
list.set(index, newValue);
fruits.set(0, "Grapes");
This changes the item at index 0 to "Grapes".
Before:
[Apple, Orange]
After:
[Grapes, Orange]
Important idea:
set() replaces a value.The get() method retrieves an item from the ArrayList.
list.get(index);
System.out.println(fruits.get(1));
Orange
Important idea:
get() lets you look at a value stored at a certain index.The size() method tells you how many items are in the ArrayList.
list.size();
System.out.println(fruits.size());
2
Important idea:
size() gives the number of elements in the list.import java.util.ArrayList;
public class ArrayListNotes {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<String>();
// add()
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
System.out.println("After add: " + fruits);
// remove()
fruits.remove(1);
System.out.println("After remove: " + fruits);
// set()
fruits.set(0, "Grapes");
System.out.println("After set: " + fruits);
// get()
System.out.println("Item at index 1: " + fruits.get(1));
// size()
System.out.println("Size of list: " + fruits.size());
}
}
After add: [Apple, Banana, Orange]
After remove: [Apple, Orange]
After set: [Grapes, Orange]
Item at index 1: Orange
Size of list: 2
import java.util.ArrayList;
If the list has 3 items, valid indexes are:
0, 1, 2
If:
list.size() == 3
The last index is:
2
Think of an ArrayList like a row of lockers:
add() = add a new locker at the endremove() = remove a lockerset() = replace what is inside a lockerget() = look inside a lockersize() = count how many lockers there areadd() do in an ArrayList?ArrayList?set() add a new item or replace an existing one?get(0) return?ArrayList has 4 items, what will size() return?