The set()
method is a fundamental operation in the Java ArrayList
class. It allows you to replace an element at a specific position in the list with a new value, making it essential for updating or modifying the contents of an ArrayList
without altering its structure.
What Is the set() Method in ArrayList?
- The
set()
method replaces the element at a given index with a new specified element. - It is useful when you want to update the value at a particular position while preserving the order and size of the list.
- The method returns the element that was replaced.
Syntax
public E set(int index, E element)
Where:
index
is the position of the element to replace (zero-based).element
is the new value to store at that position.E
is the type of elements contained in the list.
Parameters
Parameter | Description |
---|---|
index | The position of the element to replace. Must be between 0 and size() - 1 . |
element | The new value to be assigned at the given index. |
Return Value
- Returns the element that was previously at the specified position.
Exceptions
IndexOutOfBoundsException
: Thrown if the specified index is less than 0 or greater than or equal to the list size.- No checked exceptions for standard usage.
How Does set() Work Internally?
- Validates that the index is within bounds.
- Sets the value at the specified index to the new element.
- Returns the old element that was replaced.
Examples of the set() Method
1. Replace an Element by Index
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> cars = new ArrayList<>(); cars.add("Volvo"); cars.add("BMW"); cars.add("Ford"); cars.add("Mazda"); // Replace the first element (index 0) String oldCar = cars.set(0, "Opel"); // Output: [Opel, BMW, Ford, Mazda] System.out.println("Updated list: " + cars); // Output: Volvo System.out.println("Replaced element: " + oldCar); } }
Output:
Updated list: [Opel, BMW, Ford, Mazda]
Replaced element: Volvo
2. Update Multiple Elements
import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); numbers.add(5); // [1, 2, 3, 4, 5] System.out.println("Before: " + numbers); // Update elements at positions 0, 2, 4 numbers.set(0, 10); numbers.set(2, 30); numbers.set(4, 50); // [10, 2, 30, 4, 50] System.out.println("After: " + numbers); } }
3. set() vs add() (Key Difference)
import java.util.ArrayList; public class Comparison { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); list.set(1, "z"); // Replaces element at index 1 ("b") with "z" System.out.println("After set: " + list); // [a, z, c] list.add(1, "y"); // Inserts "y" at index 1, shifts elements right System.out.println("After add: " + list); // [a, y, z, c] } }
Output:
After set: [a, z, c]
After add: [a, y, z, c]
The set()
method replaces the value, while add()
inserts a value and shifts the rest.
Important Notes
- Index must be valid (0 to
size() - 1
). set()
is for updating values, not inserting new ones.- For numeric lists, be careful:
set(1, 100)
replaces the element at index 1, NOT adds a new element. - The old (replaced) element is returned, allowing you to use or log the previous value.
- No list resizing occurs; size remains unchanged.
Summary
Aspect | Details |
---|---|
Method Purpose | Replace the element at specified index |
Syntax | list.set(int index, E element) |
Return Value | Previous element at the given index |
Modifies List Size? | No (updates in-place) |
Exception | IndexOutOfBoundsException if index invalid |
Typical Use Cases | Update entries, fix values, in-place edits |
Typical Use Cases
- Editing list items: Update user details, configuration values, or game scores.
- Batch updates: Loop through a list and transform or correct multiple elements.
- Swapping values: When reordering or modifying list contents.
- Data correction: Fixing values by position after validation.