How to Modify Element or Elements of an ArrayList in Java

By Saruque Ahamed Mollick

While working with ArrayList in Java, You might have faced some problems like, suppose you got a huge number of elements in your ArrayList and you have to modify a particular element from your list.

So how to do that?

In this post, we are going to learn the easy method to update or modify or you can say replace element as per your desire in Java program.

To understand this I will go with an example.
Assume you have an ArrayList named list.

The list contains the following elements:

[CodeSpeedy, ArrayList, Java]

But you need the list like this one:

[CodeSpeedy, ArrayList, J2EE]

So, you have to modify the last one. That means you need to change the last element which is “Java” whose index number is 2. (As index number starts with 0)

How To Convert An ArrayList to Array In Java



 

Java Program To Update Element in an ArrayList:

import java.util.ArrayList;
public class Arraylistupdate {
    public static void main(String args[]){
        ArrayList<String> list=new ArrayList<String>();
        list.add("CodeSpeedy");
        list.add("ArrayList");
        list.add("Java");
        System.out.println("before modify: "+list);
        list.set(2, "J2EE");
        System.out.println("after modify: "+list);
        
    }
    
}

Output:

run:
before modify: [CodeSpeedy, ArrayList, Java]
after modify: [CodeSpeedy, ArrayList, J2EE]
BUILD SUCCESSFUL (total time: 0 seconds)

How to Increase and Decrease Current Capacity (Size) of ArrayList in Java

 

Explanation:

list.set(2, "J2EE");

This is the main line which is responsible for updating an element.
in set() method we have to put two values separated by a comma.
The first one is the index of the element which you want to be updated.
And the second value is for new updated element you want to be inserted in the list instead of the old one.

here 2 is the index of Java.

And then we put J2EE so that Java got replaced by J2EE.

We added ” ” these because its a String type ArrayList.
In the case of Integer, we don’t need to put those double quotations.

Finding an ArrayList in Java is Empty or Not

 

Leave a Reply

Your email address will not be published. Required fields are marked *