Replacing Element at a Specific Index in a Java ArrayList

06 May 2023 Balmiki Mandal 0 Core Java

.

How to Replace an Element at a Specific Index in a Java ArrayList?

The ArrayList class in Java provides the set() method for replacing an element at a specific index in an ArrayList. The set() method takes two parameters – the index and new value that needs to be added at that index. This method is more efficient as compared to using the remove() and then adding the new element.

Syntax

list.set(index, element);

Example

Let's take an example to understand how it works. Let's assume we have an ArrayList with four elements and we need to change the third element from 'C' to 'D'.

import java.util.ArrayList; 
public class MyMain { 
    public static void main(String[] args) { 
        // create an array list 
        ArrayList<String> myarrlist = new ArrayList<String>(); 
          
        // Add some elements to the list 
        myarrlist.add("A"); 
        myarrlist.add("B"); 
        myarrlist.add("C"); 
        myarrlist.add("D"); 
          
        // Print the list before updating 
        System.out.println("Original list: " + myarrlist); 
          
        // Replace the 3rd element with 'D' 
        myarrlist.set(2, "D"); 
          
        // Print the list after updating 
        System.out.println("Updated list: " + myarrlist); 
    } 
}

Output:

Original list: [A, B, C, D] 
Updated list: [A, B, D, D]

In this example, we have replaced the third element from 'C' to 'D' using the set() method.

Conclusion

We saw how easy it is to replace an element at a specific index using the set() method of the ArrayList class in Java.

Author
BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.