ArrayList
- Java course
- Beginner
- Lesson 65/116
- 4 min
Learn dynamic arrays with ArrayList.
Dynamic array: ArrayList
When you want a list that grows automatically instead of a fixed-length int[], you use ArrayList. The java.util.ArrayList class expands itself as you add elements.
ArrayList<String> names = new ArrayList<>();
names.add("Ayşe");
names.add("Mehmet");
// [Ayşe, Mehmet]The type goes inside angle brackets: ArrayList<String>. This guarantees only String can be added. For primitive types you use wrapper classes: Integer, Double, Boolean.
Why is ArrayList practical?
With fixed-length arrays, adding an element means creating a new array and copying the old one. ArrayList does this for you; it offers ready methods like add, remove and size.
ArrayList<Integer> nums = new ArrayList<>();
nums.add(10);
nums.add(20);
int first = nums.get(0);
// first = 10To print the list, just System.out.println(nums); the toString method is called automatically and produces a bracketed output.
Practice Build a customer list
Create an ArrayList<String>, add "Ayşe", "Mehmet" and "Zeynep", then print the list.
Starter code
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList<String>
// Add three names
// Print the list
}
}Sample solution
ArrayList<String> names = new ArrayList<>();
names.add("Ayşe");
names.add("Mehmet");
names.add("Zeynep");
System.out.println(names);Expected output
[Ayşe, Mehmet, Zeynep]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: declare the list
ArrayList<String> names = new ArrayList____();
ArrayList<String> names = new ArrayList<>();
Explanation: The diamond operator <> infers the type on the right.
2 Match method to purpose
| Term | Meaning |
|---|---|
add(x) |
Adds an element to the list |
get(i) |
Returns the element at index i |
size() |
Returns the number of elements |
remove(i) |
Removes the element at index i |
3 What is needed to add a primitive int to an ArrayList?
- Convert it to an int[] first
- Use the Integer wrapper Correct answer
- Declare the list as ArrayList<int>
- Make the list static
Explanation: Generics do not accept primitive types; use Integer.