Java Program to Change an Element in ArrayList

In the previous article, we have seen Java Program to Remove Duplicates from ArrayList

In this article we are going to see how we can change an element in an ArrayList in java.

Java Program to Change an Element in ArrayList

We can change elements from an arraylist using the set() method in Java. We need to pass the method with the index of the element and the element to be replaced with.

Synatx: ArrayList_Name.set(arrayList_index,"New_Element")

Where,

  • ArrayList_Name refers to the actual arraylist.
  • arrayList_index refers to the index of the arraylist to be replaced
  • "New_Element" refers to the new element which will replace the old element.

Let’s see the program to understand it more clearly.

Java Program to Change an Element in ArrayList By Using set() Method

Approach:

  • Create an arraylist in Java and add some elements to it.
  • Print the arraylist.
  • Change a element by passing the index and the element into the set( ) method.
  • Print the new list.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Creating an empty ArrayList
        ArrayList<String> arr = new ArrayList<String>();
        // Adding elements to the arrayList
        arr.add("One");
        arr.add("Two");
        arr.add("Three");
        // Displaying the list
        System.out.println("Arraylist"+arr);
        // Changing the element 'three' to '3' at index 2
        arr.set(2,"3");
        // Displaying the list
        System.out.println("Arraylist after changing an element"+arr);
    }
}

Output:

Arraylist[One, Two, Three]
Arraylist after changing an element[One, Two, 3]

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Related Java Programs: