Skip to content

WebDevHubs

  • Home
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • Java
  • Selenium
  • PHP
  • Python
  • Programs
  • Toggle search form

Java ArrayList set() Method

Posted on July 24, 2025July 24, 2025 By Admin No Comments on Java ArrayList set() Method

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

ParameterDescription
indexThe position of the element to replace. Must be between 0 and size() - 1.
elementThe 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

AspectDetails
Method PurposeReplace the element at specified index
Syntaxlist.set(int index, E element)
Return ValuePrevious element at the given index
Modifies List Size?No (updates in-place)
ExceptionIndexOutOfBoundsException if index invalid
Typical Use CasesUpdate 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.
Java Tags:Java-ArrayList, Java-ArrayList-Method, Java-Collections

Post navigation

Previous Post: Java ArrayList retainAll() Method
Next Post: Java ArrayList size() Method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java ArrayList
  • Java ArrayList Methods
  • Java ArrayList add() Method
  • Java ArrayList addAll() Method
  • Java ArrayList clear() Method
  • Java ArrayList clone() Method
  • Java ArrayList contains() Method
  • Java ArrayList ensureCapacity() Method
  • Java ArrayList forEach() Method
  • Java ArrayList get() Method
  • Java ArrayList indexOf() Method
  • Java ArrayList isEmpty() Method
  • Java ArrayList iterator() Method
  • Java ArrayList lastIndexOf() Method
  • Java ArrayList listIterator() Method
  • Java ArrayList remove() Method
  • Java ArrayList removeAll() Method
  • Java ArrayList removeIf() Method
  • Java ArrayList replaceAll() Method
  • Java ArrayList retainAll() Method
  • Java ArrayList set() Method
  • Java ArrayList size() Method
  • Java ArrayList sort() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList subList() Method
  • Java ArrayList toArray() Method
  • Java ArrayList trimToSize() Method

Recent Posts

  • Java ArrayList trimToSize() Method
  • Java ArrayList toArray() Method
  • Java ArrayList subList() Method
  • Java ArrayList spliterator() Method
  • Java ArrayList sort() Method

Recent Comments

No comments to show.

Important Pages

  • About Us
  • Contact Us
  • Terms of Use
  • Privacy Policy

Web Development

  • HTML
  • CSS
  • JavaScript
  • PHP

Programming Languages

  • Java
  • Python
  • PHP
  • Programs

Others

  • Selenium
  • Lodash
  • Java ArrayList
  • JavaScript Array Methods

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme