Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ArrayList set() method
Syntax and Examples


Introduction

The set() method in Java's ArrayList is your tool for modifying existing elements within the list. Think of an ArrayList like a row of numbered boxes – each box holds one item. The set() method lets you replace what's currently in a specific box with something new.

Syntax


public E set(int index, E element)

Parameters

Parameter Description
index The index of the element you want to replace. The index is zero-based, meaning the first element has an index of 0.
element The new element that will be placed at the specified index. It must be of the same type as the elements stored in the ArrayList (or a compatible type).

Return Value

The set() method returns the original element that was present at the specified index before it was replaced. It doesn't modify the list itself; it just *returns* what was there originally.

Examples

Replacing a String in an ArrayList

This example demonstrates how to replace an existing string element within an ArrayList using the set() method.


import java.util.ArrayList;

public class SetExample {
    public static void main(String[] args) {
        // Create an ArrayList of Strings
        ArrayList<String> names = new ArrayList<>(
                "Alice", "Bob", "Charlie"
        );

        System.out.println("Original list: " + names);

        // Replace the element at index 1 (which is "Bob") with "Ram"
        String originalName = names.set(1, "Ram");

        System.out.println("Modified list: " + names);
        System.out.println("Original name at index 1: " + originalName);
    }
}


Original list: [Alice, Bob, Charlie] 
Modified list: [Alice, Ram, Charlie] 
Original name at index 1: Bob

In this example, we first created an ArrayList named 'names'. We then used the set() method to change the element at index 1 (originally "Bob") to "Ram". The set() method returned the original value ("Bob"), which was stored in the variable `originalName` and printed.

Replacing a Number in an ArrayList

This example shows how to replace a numeric element within an ArrayList, illustrating that set() works with various data types.


import java.util.ArrayList;

public class SetNumberExample {
    public static void main(String[] args) {
        // Create an ArrayList of Integers
        ArrayList<Integer> numbers = new ArrayList<>(
                10, 20, 30
        );

        System.out.println("Original list: " + numbers);

        // Replace the element at index 0 (which is 10) with 5
        Integer originalNumber = numbers.set(0, 5);

        System.out.println("Modified list: " + numbers);
        System.out.println("Original number at index 0: " + originalNumber);
    }
}


Original list: [10, 20, 30] 
Modified list: [5, 20, 30] 
Original number at index 0: 10

Here, we're using an ArrayList of Integers. The set() method replaces the element at index 0 (originally 10) with 5, and stores the original value in `originalNumber`.

Handling Index OutOfBoundsException

This example demonstrates what happens when you try to use an invalid index with the set() method. It's crucial to ensure your index is within the bounds of the list.


import java.util.ArrayList;

public class SetOutOfBoundsExample {
    public static void main(String[] args) {
        // Create an ArrayList of Strings
        ArrayList<String> names = new ArrayList<>(
                "Alice", "Bob"
        );

        try {
            // Attempt to replace the element at index 2 (which doesn't exist)
            names.set(2, "Charlie"); // This will throw an IndexOutOfBoundsException
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }

        System.out.println("List after attempted modification: " + names);
    }
}


Error: Index 2 out of bounds for length 2
List after attempted modification: [Alice, Bob]

Because our list only has two elements (indices 0 and 1), trying to set the element at index 2 results in an IndexOutOfBoundsException. It's important to check if your index is valid before calling set(), usually by using the `size()` method of the ArrayList.


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M