We import ArrayList, from java dot util. The type in angle brackets says what the list holds, here strings. Add puts an item at the end. Size counts items, and get reads one by index. Set replaces an item, and add with an index inserts one. Remove takes one out. Contains and index of search the list. Run it. The list grows, changes, and prints itself nicely.
Main.javajava
import java.util.ArrayList;public class Main { public static void main(String[] args) { ArrayList<String> tasks = new ArrayList<>(); tasks.add("Buy milk"); tasks.add("Call Sam"); tasks.add("Write report"); System.out.println(tasks); System.out.println("Size: " + tasks.size()); System.out.println("First: " + tasks.get(0)); tasks.set(1, "Call Sam back"); tasks.add(0, "Wake up"); tasks.remove("Buy milk"); System.out.println(tasks); System.out.println("Has report? " + tasks.contains("Write report")); System.out.println("Index of report: " + tasks.indexOf("Write report")); }}
Output
[Buy milk, Call Sam, Write report]
Size: 3
First: Buy milk
[Wake up, Call Sam back, Write report]
Has report? true
Index of report: 2
For each works with lists, just like arrays. Or loop with an index, using size and get. List dot of makes a list quickly, but that list can't be changed. Run it. The loops work. But adding to the fixed list crashes, with an unsupported operation exception.
Main.javajava
import java.util.ArrayList;import java.util.List;public class Main { public static void main(String[] args) { List<String> names = new ArrayList<>(List.of("Ana", "Ben", "Chen")); for (String n : names) { System.out.println("Hello, " + n); } for (int i = 0; i < names.size(); i++) { System.out.println(i + ": " + names.get(i)); } List<String> fixed = List.of("red", "green"); System.out.println(fixed); fixed.add("blue"); }}
Output
Hello, Ana
Hello, Ben
Hello, Chen
0: Ana
1: Ben
2: Chen
[red, green]
Exception in thread "main" java.lang.UnsupportedOperationException
at Main.main(Main.java:14)
ArrayList is a list that grows. Add, get, set, remove, and size are the main methods. List dot of makes a fixed list. Next, the angle brackets, called generics.