Java.util.ArrayList.set() Method

Published by user on

Java.util.ArrayList.set() method replaces the element at the specified index with the new element.

Syntax:

Let’s look the syntax of Java.util.ArrayList.set().

public int set(int index, E e)

Parameters:

index – This is the position of the element to be replaced,
e – This is the element to be stored at the specified position.

Returns:

It returns the element which was replaced by the newly specified element.

Example 1:

This example demonstrates the use of the ArrayList set() method.

import java.util.ArrayList;

// This program demonstrates
// the use of ArrayList set method
public class ArrayListDemo {

        public static void main(String[] args) {
                ArrayList arrList = new ArrayList<>();
                arrList.add(11);
                arrList.add(17);
                arrList.add(32);
                arrList.add(25);
                arrList.add(80);

                System.out.println("Elements in the list :");
                for (Integer i : arrList) {
                        System.out.println("Value = " + i);
                }

                // set method replaces the element
                // 67 will be stored at index 3
                arrList.set(3, 67);

                System.out.println("Values after replacing the element :");
                for (Integer i : arrList) {
                        System.out.println("Value = " + i);
                }
        }
}

Output:

Elements in the list :
Value = 11
Value = 17
Value = 32
Value = 25
Value = 80
Values after replacing the element :
Value = 11
Value = 17
Value = 32
Value = 67
Value = 80

Example 2:

Let’s have a look at how the set() method throws IndexOutOfBoundsException if the specified index is out of range.

import java.util.ArrayList;

// This program demonstrates
// how ArrayList set method
// throws IndexOutOfBoundException
public class ArrayListDemo {
        public static void main(String[] args) {
                ArrayList arrList = new ArrayList<>();
                arrList.add(10);
                arrList.add(20);
                arrList.add(30);
                arrList.add(40);

                System.out.println("Elements in the list :");

                for (Integer i : arrList) {
                        System.out.println("Value = " + i);
                }
                // throws IndexOutOfBoundsException
                arrList.set(9, 80);
        }
}

Output:

Elements in the list :
Value = 10
Value = 20
Value = 30
Value = 40
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 9, Size: 4
        at java.util.ArrayList.rangeCheck(Unknown Source)
        at java.util.ArrayList.set(Unknown Source)
        at ArrayListDemo.main(ArrayListDemo.java:20)
Categories: Java