Collections
Collections
Often you need to store many elements: a list of names, a list of scores, etc. Java provides collections in the java.util package. The most used is ArrayList, which implements the List interface.
List and ArrayList
List is an interface: it describes what operations a list supports. ArrayList is a concrete implementation that stores elements in a resizable array. You typically declare the variable as List and create an ArrayList:
javaimport java.util.ArrayList; import java.util.List; List<String> names = new ArrayList<>(); names.add(\"Alice\"); names.add(\"Bob\"); names.add(\"Carol\"); System.out.println(names.size()); // 3 System.out.println(names.get(0)); // Alice
List<String>means a list that can only holdStringelements. This is a generic type; it gives you type safety and avoids casting.get(index)returns the element at that index. Indices start at 0.size()returns the number of elements.
The for-each loop
To iterate over every element in a list (or any collection) without using an index, use the enhanced for loop (for-each):
javafor (String name : names) { System.out.println(name); }
Read this as: for each name in names, do something. The variable name holds the current element in each iteration.
Useful List methods
| Method | Description |
|---|---|
| add(element) | Add at the end |
| add(index, element) | Insert at index |
| get(index) | Get element at index |
| set(index, element) | Replace element at index |
| remove(index) | Remove at index, return value |
| remove(object) | Remove first matching element |
| size() | Number of elements |
| contains(object) | true if the list contains it |
Example:
javanames.set(1, \"Bob Smith\"); // replace second element names.remove(2); // remove third element boolean hasAlice = names.contains(\"Alice\");
Other collections
Besides ArrayList, the Java standard library offers LinkedList, HashSet, HashMap, and others. Each has different performance and usage. For a simple ordered list of elements, ArrayList is usually the right choice.