Java arraylist set method example

Java ArrayList set method :

set method is used to replace one element in an ArrayList in Java. In this tutorial, I will show you how to use set method with one example.

Syntax of set method :

The syntax of set method is as below :

public E set(int index, E element)

It takes two parameters : index: This is the index of the element you want to replace. element: This is the new element

Return value :

This method returns the previous element i.e. the element that is replaced.

Exception :

It throws one IndexOutOfBoundsException if the index is wrong.

Java program :

Let’s take a look at the below Java program :

import java.util.ArrayList;
import java.util.Scanner;

public class Example {

    public static void main(String[] args) {
        int position;
        char newChar;

        Scanner sc = new Scanner(System.in);

        ArrayList<character> myList = new ArrayList<>();

        myList.add('a');
        myList.add('b');
        myList.add('c');
        myList.add('d');
        myList.add('e');
        myList.add('f');

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

        System.out.println("Enter the index to modify in the list : ");
        position = sc.nextInt();
        System.out.println("Enter the new character : ");
        newChar = sc.next().charAt(0);

        myList.set(position, newChar);
        System.out.println("New list : " + myList);
    }
}

Java arraylist set

Sample Output :

Original list : [a, b, c, d, e, f]
Enter the index to modify in the list : 
3
Enter the new character : 
R
d
New list : [a, b, c, R, e, f]

Explanation :

Here, we are using one predefined list. This list holds a couple of characters. The program is taking the index as an input from the user and replaces the character at that index with another user-provided character.

set() method is the recommended way to replace an element of a Java Array. Try to go through the above example and drop one comment below if you have any queries.

Similar tutorials :