new ArrayList<>() / list.add() / set() / get()
| Since: | Java 1.2(1998) |
|---|
Methods for creating a variable-length list and adding, updating, and retrieving elements. Unlike arrays, ArrayList can dynamically change its size, making it widely used when the number of elements is not known in advance.
Syntax
import java.util.ArrayList; // Creates an empty ArrayList. new ArrayList<Type>(); // Appends an element to the end of the list. list.add(E e); // Inserts an element at the specified position. list.add(int index, E e); // Replaces the element at the specified position. list.set(int index, E element); // Returns the element at the specified position. list.get(int index);
Method List
| Method | Description |
|---|---|
| new ArrayList<>() | Creates an empty variable-length list. The type argument specifies the type of elements to store in the list. |
| add(E e) | Appends an element to the end of the list. Returns true if the element was added successfully. |
| add(int index, E e) | Inserts an element at the specified index. All subsequent elements are shifted one position to the right. |
| set(int index, E element) | Replaces the element at the specified index with a new value. Returns the element that was previously at that position. |
| get(int index) | Returns the element at the specified index. Indices are zero-based. |
Sample Code
ArrayListAddGet.java
import java.util.ArrayList;
class ArraylistAddGet {
public static void main(String[] args) {
// Create an ArrayList and add elements.
ArrayList<String> fighters = new ArrayList<>();
fighters.add("Yagami Iori");
fighters.add("Kusanagi Kyo");
fighters.add("Terry Bogard");
System.out.println(fighters); // Prints "[Yagami Iori, Kusanagi Kyo, Terry Bogard]".
// Insert an element at a specific position.
fighters.add(1, "Blue Mary"); // Inserts at index 1.
System.out.println(fighters); // Prints "[Yagami Iori, Blue Mary, Kusanagi Kyo, Terry Bogard]".
// Retrieve elements using get().
System.out.println(fighters.get(0)); // Prints "Yagami Iori".
System.out.println(fighters.get(2)); // Prints "Kusanagi Kyo".
// Update an element using set().
String old = fighters.set(0, "Goenitz"); // Replaces the first element.
System.out.println(old); // Prints the previous value: "Yagami Iori".
System.out.println(fighters); // Prints "[Goenitz, Blue Mary, Kusanagi Kyo, Terry Bogard]".
// Example using a list of numbers.
ArrayList<Integer> nums = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
nums.add(i * 10);
}
System.out.println(nums); // Prints "[10, 20, 30, 40, 50]".
// Accessing an out-of-bounds index throws an exception.
// System.out.println(nums.get(10)); // Throws IndexOutOfBoundsException.
}
}
ArraylistAddGet.java
javac ArraylistAddGet.java java ArraylistAddGet [Yagami Iori, Kusanagi Kyo, Terry Bogard] [Yagami Iori, Blue Mary, Kusanagi Kyo, Terry Bogard] Yagami Iori Kusanagi Kyo Yagami Iori [Goenitz, Blue Mary, Kusanagi Kyo, Terry Bogard] [10, 20, 30, 40, 50]
Common Mistakes
Common Mistake 1: IndexOutOfBoundsException (accessing a non-existent index)
get() and set() use zero-based indices. Accessing an index equal to or greater than the list's size throws an IndexOutOfBoundsException.
IndexNg.java
import java.util.ArrayList;
class IndexNg {
public static void main(String[] args) {
ArrayList<String> fighters = new ArrayList<>();
fighters.add("Yagami Iori");
fighters.add("Kusanagi Kyo");
fighters.add("Terry Bogard");
System.out.println(fighters.get(3));
}
}
The command looks like this:
javac IndexNg.java java IndexNg Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
Check the list size with size() before accessing an element to ensure the index is within the valid range (0 or more and less than size()).
IndexOk.java
import java.util.ArrayList;
class IndexOk {
public static void main(String[] args) {
ArrayList<String> fighters = new ArrayList<>();
fighters.add("Yagami Iori");
fighters.add("Kusanagi Kyo");
fighters.add("Terry Bogard");
int idx = 3;
if (idx < fighters.size()) {
System.out.println(fighters.get(idx));
} else {
System.out.println("Index " + idx + " is out of bounds (size=" + fighters.size() + ")");
}
}
}
The command looks like this:
javac IndexOk.java java IndexOk Index 3 is out of bounds (size=3)
Common Mistake 2: Adding elements to the list returned by Arrays.asList causes UnsupportedOperationException
The list returned by Arrays.asList() is fixed-size. Attempting to add or remove elements throws an UnsupportedOperationException.
AsListNg.java
import java.util.Arrays;
import java.util.List;
class AsListNg {
public static void main(String[] args) {
List<String> fighters = Arrays.asList("Blue Mary", "Goenitz");
fighters.add("Kusanagi Kyo");
}
}
The command looks like this:
javac AsListNg.java java AsListNg Exception in thread "main" java.lang.UnsupportedOperationException
When you need to add or remove elements, wrap the result of Arrays.asList() with new ArrayList<>() to create a mutable list.
AsListOk.java
import java.util.ArrayList;
import java.util.Arrays;
class AsListOk {
public static void main(String[] args) {
ArrayList<String> fighters = new ArrayList<>(Arrays.asList("Blue Mary", "Goenitz"));
fighters.add("Kusanagi Kyo");
System.out.println(fighters);
}
}
The command looks like this:
javac AsListOk.java java AsListOk [Blue Mary, Goenitz, Kusanagi Kyo]
Notes
ArrayList is the most commonly used collection class in Java. Internally it is backed by an array, so appending elements (add()) and retrieving elements (get()) run in O(1) time. However, inserting an element in the middle requires shifting all subsequent elements, so it runs in O(n) time.
Primitive types (int, double, etc.) cannot be stored directly. Use their wrapper classes (Integer, Double, etc.) instead. Thanks to Java's autoboxing feature, writing nums.add(1) automatically converts the value to Integer.
To remove elements or check the list size, see remove() / clear() / size(). To search for elements, see contains() / indexOf().
If you find any errors or copyright issues, please contact us.