The ArrayList.set(int index, E element) method replaces the element at the specified 0-based position with element in O(1) constant time and returns the element that was previously stored at that position.
Related List Operations: Unlike ArrayList.add(int index, E) (which inserts a new slot and shifts subsequent elements right), set() overwrites an existing slot without changing ArrayList.size(). To read an element without modifying it, use ArrayList.get(). To locate an element's index before updating it, use ArrayList.indexOf().
Declared in java.util.ArrayList<E>:
// Replaces the element at the specified 0-based position and returns the old element
public E set(int index, E element)
| Element | Type / Complexity | Operational Rule |
|---|---|---|
index |
int |
0-based position of the element to replace (0 <= index < size()). |
element |
E (nullable) |
New element to store at the specified position. |
| Return Value | E (O(1) time) |
Returns the old element that was previously at index. |
Calling languages.set(1, "Python") replaces "PHP" at index 1 with "Python". Because set() returns the displaced element, you can assign its return value to inspect or log what was overwritten:
ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "PHP", "HTML"));
System.out.println("Initial: " + languages); // [Java, PHP, HTML]
languages.set(1, "Python"); // Replaces "PHP" at index 1
System.out.println("After #1: " + languages); // [Java, Python, HTML]
String replaced = languages.set(0, "JQuery"); // Captures old value "Java"
System.out.println("Replaced: " + replaced); // Java
System.out.println("After #2: " + languages); // [JQuery, Python, HTML]Terminal Output:
Initial: [Java, PHP, HTML]
After #1: [Java, Python, HTML]
Replaced: Java
After #2: [JQuery, Python, HTML]
set(index, e) overwrites an existing slot in O(1) time without changing the list length, whereas add(index, e) inserts a new slot, shifts existing elements right in O(n) time, and increases size() by 1:
ArrayList<String> a = new ArrayList<>(Arrays.asList("A", "B", "C"));
a.set(1, "X"); // Overwrites index 1 in O(1); size stays 3
System.out.println("After set(1, 'X'): " + a + " (size=" + a.size() + ")");
ArrayList<String> b = new ArrayList<>(Arrays.asList("A", "B", "C"));
b.add(1, "X"); // Inserts at index 1 and shifts tail right in O(n); size becomes 4
System.out.println("After add(1, 'X'): " + b + " (size=" + b.size() + ")");Terminal Output:
After set(1, 'X'): [A, X, C] (size=3)
After add(1, 'X'): [A, X, B, C] (size=4)
If index < 0 or index >= size(), set() throws an IndexOutOfBoundsException. Notice that for a 3-element list (indices 0, 1, 2), calling languages.set(3, "Rust") fails because slot 3 does not exist yet:
ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "PHP", "HTML"));
try {
// Valid indices are 0, 1, 2. Index 3 (4th position) is out of bounds!
languages.set(3, "Rust");
} catch (IndexOutOfBoundsException ex) {
System.out.println("Caught on set(3): " + ex.getMessage());
}Terminal Output:
Caught on set(3): Index 3 out of bounds for length 3
When you want to update every element in an ArrayList using a transformation rule, Java 8+ list.replaceAll(UnaryOperator<E>) is cleaner than a manual loop of list.set(i, fn(list.get(i))):
ArrayList<String> tags = new ArrayList<>(Arrays.asList("java", "sql", "html"));
// Java 8+ replaceAll() applies a function to every slot in place:
tags.replaceAll(s -> s.toUpperCase());
System.out.println("Uppercased: " + tags);Terminal Output:
Uppercased: [JAVA, SQL, HTML]
Selecting the right update method for your use case:
| Method | Time Complexity | Effect & Best Use Case |
|---|---|---|
list.set(index, newVal) |
O(1) |
Replaces a single known index and returns the old value. |
list.replaceAll(operator) |
O(n) |
Transforms every element in the list in place. |
Collections.replaceAll(list, old, nw) |
O(n) |
Replaces all occurrences of old with nw by value. |
listIterator.set(newVal) |
O(1) |
Updates the current element during bidirectional iteration. |
Because list.set(j, val) returns the previous value at index j, you can swap two elements at indices i and j in a single nested expression list.set(i, list.set(j, list.get(i))) (which is exactly how Collections.swap() is implemented in the JDK):
public class FastElementSwap {
public static <E> void swapElements(ArrayList<E> list, int i, int j) {
list.set(i, list.set(j, list.get(i)));
}
public static void main(String[] args) {
ArrayList<String> ranks = new ArrayList<>(Arrays.asList("First", "Second", "Third"));
swapElements(ranks, 0, 2);
System.out.println("Swapped 0 and 2: " + ranks);
}
}Terminal Output:
Swapped 0 and 2: [Third, Second, First]
Combine indexOf() with set() to replace the first occurrence of a value, or use Collections.replaceAll() to replace every occurrence:
public class UpdateByValue {
public static void main(String[] args) {
ArrayList<String> status = new ArrayList<>(Arrays.asList("NEW", "WAIT", "NEW"));
int idx = status.indexOf("NEW");
if (idx != -1) status.set(idx, "ACTIVE");
Collections.replaceAll(status, "NEW", "DONE");
System.out.println("Updated: " + status);
}
}Terminal Output:
Updated: [ACTIVE, WAIT, DONE]
Passing an initial capacity of 10 to new ArrayList<>(10) or ensureCapacity(10) does not create 10 elements—size() is still 0! Calling list.set(0, "A") on an empty list throws an IndexOutOfBoundsException. Use list.add("A") to populate elements first.
While list.add(list.size(), item) is valid (appending at the end), list.set(list.size(), item) is always out of bounds because the highest existing element index is list.size() - 1.
Compile and run this verification class in any Java environment:
public class ArrayListSetFullDemo {
public static void main(String[] args) {
ArrayList<Integer> scores = new ArrayList<>(Arrays.asList(70, 80, 90));
int old = scores.set(1, 85);
if (old == 80 && scores.get(1) == 85 && scores.size() == 3) {
System.out.println("Check 1 Passed: set(1, 85) returned 80 and kept size 3.");
}
scores.set(2, null);
if (scores.get(2) == null) {
System.out.println("Check 2 Passed: Setting null value verified.");
}
System.out.println("All ArrayList.set() verification checks passed!");
}
}Terminal Output:
Check 1 Passed: set(1, 85) returned 80 and kept size 3.
Check 2 Passed: Setting null value verified.
All ArrayList.set() verification checks passed!
No! Because set() only replaces an existing slot without changing the list's size, it is not a structural modification and does not increment modCount.
Yes. ArrayList permits null elements, so list.set(index, null) overwrites slot index with null and returns the previous value.
Yes! Even though Arrays.asList() returns a fixed-size list that rejects add() and remove(), it does support set(index, element) (and writes directly through to the backing array).
Combine set() and get(): counts.set(i, counts.get(i) + 1);.
O(1) time.ArrayList.set().size() - 1).ArrayList.ArrayList methods.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.