Java ArrayList.set(): Updating Elements in Place by Index

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().

1. Syntax, Method Signature & O(1) Mechanics 🔝

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.

2. Basic Element Replacement & Capturing the Old Value 🔝

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]

3. Critical Distinction: set(index, E) vs add(index, E) 🔝

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)

4. Exception Handling: IndexOutOfBoundsException 🔝

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

5. Transforming Every Element in Place with replaceAll() 🔝

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]

6. Comparison: Ways to Update Elements in ArrayList 🔝

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.

7. Production Recipe: One-Line Element Swap Using set() Return Value 🔝

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]

8. Practical Recipe: Updating Elements by Value instead of Index 🔝

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]

9. Common Developer Pitfalls & Traps 🔝

Calling set() on an Empty List After new ArrayList<>(10)

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.

Boundary Difference at index == size()

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.

10. Complete Compilable Java Program 🔝

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!

11. Frequently Asked Questions (FAQ) 🔝

Does ArrayList.set() throw ConcurrentModificationException if called during a for-each loop?

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.

Can I pass null as the new element in list.set(index, null)?

Yes. ArrayList permits null elements, so list.set(index, null) overwrites slot index with null and returns the previous value.

Does list.set() work on Arrays.asList()?

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).

How do I increment an Integer stored at index i in an ArrayList<Integer>?

Combine set() and get(): counts.set(i, counts.get(i) + 1);.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer