coderolls Staff
coderolls Staff Hi 👋🏼, At coderolls we write tutorials about Java programming language and related technologies.

How To Change An Element In ArrayList?

This article will show how to change an element in ArrayList.

Introduction

In the previous tutorial, we have seen how we can add an element to the ArrayList. But, if we wish to change an element from the ArrayList, we can use the set() method.

We know that ArrayList is an indexed collection. So we can access any particular element by its index and change it.

set() method

The set() method has a signature as public E set(int index, E element).

This method accepts the index as int and an element that needs to be set at that particular index.

The set() method has a return type as E which means it will return an element. The set() method returns the element previously at the specified position.

Below, we will see a Java program to change (set) an element in ArrayList.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.gaurav.ExProject.ArrayList;

import java.util.ArrayList;

/**
 * A Java program to change an element at 
 * particular index in ArrayList.
 * 
 * We can use 'public E set(int index, E element)' method
 * to change an element.
 * 
 * @author coderolls.com
 *
 */
public class ArrayListSetExample {

  public static void main(String[] args) {
    ArrayList<String> arrayList = new ArrayList<String>();
    
    //adding elements to the arrayList using the normal add() method
    arrayList.add("Gaurav");
    arrayList.add("Shyam");
    arrayList.add("Pradnya");
    
    System.out.println(arrayList);// [Gaurav, Shyam, Pradnya]
    
    // change an element at index 1
    arrayList.set(1, "Saurav");
    
    System.out.println(arrayList); // [Gaurav, Saurav, Pradnya]
  }
}

Output:

1
2
[Gaurav, Shyam, Pradnya]
[Gaurav, Saurav, Pradnya]

Explanation

  1. In the above program, I have added three strings ("Gaurav", "Shyam", "Pradnya") to the arrayList. We can see this by printing the arrayList.
  2. I want to change the element at index 1. So, I have provided the index as 1, and the new element i.e. String "Saurav" as arguments to the set() method.
  3. On printing the arrayList again, we can see the change element at index 1.

Conclusion

So we can change the element in ArrayList at a particular index by using the set() method.

The set method signature is as follows

1
public E set(int index, E element)

The set() returns the previously present element in the ArrayList.

So, we have seen how to add an element and how to change an element in the ArrayList, next we will see how we can remove an element from ArrayList in Java.


The example Java programs given in the above tutorial can be found at this GitHub Repository.

Join Newsletter
Get the latest tutorials right in your inbox. We never spam!

comments powered by Disqus