How to replace element in ArrayList

We can replace element in arraylist using ArrayList Set() method. This method replaces the element at the specified position in this list with the specified element.

Syntax :

public E set(int index, E element) {

}
  • Parameters:
    index – index of the element to replace
    element – element to be stored at the specified position
  • Returns value:
    the element previously at the specified position
  • Exception – It throws following exception
    IndexOutOfBoundsException – if the index is out of range (index < 0 || index >= size())

Let’s see code for this

import java.util.ArrayList;
public class ReplaceElement {

public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();

// add element in arraylist

arr.add("c");
arr.add("php");
arr.add("html");
arr.add("java");
arr.add("delhi");
arr.add("india");

// print arraylist

System.out.println("before replace arrayList is = " + arr);

/*
* Replaces the element at the specified
*  position in this list with the specified element.
*/

arr.set(2,"Mysql");

System.out.println("after replace arrayList is = " + arr);

}

}

Output:

before replace arrayList is = [c, php, html, java, delhi, india]

after replace arrayList is = [c, php, Mysql, java, delhi, india]

Leave a Reply

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

− 4 = 2