ArrayList.set(int, E) in Java

ArrayList.set(int, E): This method is available in java.util.ArrayList class of Java.

Syntax:

E java.util.ArrayList.set(int index, E element)

This method takes two arguments. This method replaces the element at the specified position in this list with the specified element.

Parameters: Two parameters are required for this method.

index: index of the element to replace.

element: element to be stored at the specified position.

Returns: the element previously at the specified position.

Throws:

IndexOutOfBoundsException - if the index is out of range(index < 0 || index >= size())

Approach 1: When no exception

Java


Output:

1516 2 3 


Approach 2: IndexOutOfBoundsException 

Java

import java.util.ArrayList;

public class ArrayListset {
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.set(4, 1516);

        arr.forEach((n -> System.out.print(n + " ")));

    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 4 out of bounds for length 3 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248) at java.base/java.util.Objects.checkIndex(Objects.java:359) at java.base/java.util.ArrayList.set(ArrayList.java:441)


No comments:

Post a Comment