Java ArrayList
An array has a fixed length: once created, it cannot grow. Most programs, though, do not know in advance how many items they will store: the products in a cart, the names typed by a user, the lines of a file. An ArrayList is a list that grows and shrinks as you add and remove items. It is the collection Java programmers use most.
Creating a list and adding items
ArrayList is in java.util. In angle brackets you write the type of the items; this is called a generic type, explained in Generics. The type must be a class, so for numbers you write Integer, the wrapper class:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cities = new ArrayList<>();
cities.add("Chennai");
cities.add("Jaipur");
cities.add("Surat");
System.out.println(cities);
System.out.println(cities.size());
System.out.println(cities.get(1));
}
}[Chennai, Jaipur, Surat] 3 Jaipur
add puts an item at the end, size() gives the number of items, and get(i) reads the item at index i, starting at 0 like an array. Printing a list shows all its items, with no need for Arrays.toString.
Changing and removing items
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> tasks = new ArrayList<>();
tasks.add("shop");
tasks.add("cook");
tasks.add("study");
tasks.add(1, "clean");
System.out.println(tasks);
tasks.set(0, "buy milk");
tasks.remove("cook");
tasks.remove(0);
System.out.println(tasks);
System.out.println(tasks.contains("study"));
System.out.println(tasks.indexOf("study"));
tasks.clear();
System.out.println(tasks.isEmpty());
}
}[shop, clean, cook, study] [clean, study] true 1 true
add(index, item) inserts at a position and moves the rest along. remove works with an item or with an index. Note that for an ArrayList<Integer>, remove(1) removes the element at index 1; to remove the number 1 write remove(Integer.valueOf(1)).
Looping over a list
The for-each loop works exactly as with arrays:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> marks = new ArrayList<>();
marks.add(72);
marks.add(88);
marks.add(65);
int total = 0;
for (int m : marks) {
total += m;
}
System.out.println("Average: " + (double) total / marks.size());
}
}Average: 75.0
Do not remove items inside a for-each loop over the same list: Java stops with a ConcurrentModificationException. The Iterator topic shows the safe way, and marks.removeIf(m -> m < 70) does it in one line using a lambda.
Sorting and quick lists
Collections.sort sorts a list, and List.of creates a small fixed list in one line. A fixed list cannot be changed, but you can copy it into an ArrayList:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> fixed = List.of("pear", "apple", "fig");
ArrayList<String> fruits = new ArrayList<>(fixed);
fruits.add("banana");
Collections.sort(fruits);
System.out.println(fruits);
Collections.reverse(fruits);
System.out.println(fruits);
System.out.println(Collections.max(fruits));
}
}[apple, banana, fig, pear] [pear, fig, banana, apple] pear
The variable type is often written as the interface List (List<String> list = new ArrayList<>();): the code then works with any kind of list, such as the LinkedList of the next topic.
Practice exercises
- Read five names from the user into an ArrayList and print them in alphabetical order.
- Remove all names shorter than four letters from a list with
removeIf. - Store some prices in an
ArrayList<Double>and print the most expensive one withCollections.max.