Java program to replace element within the ArrayList

In this java program, we are going to learn how to replace element of an ArrayList? Here, we have an ArrayList and replace element of it. By IncludeHelp Last updated : December 31, 2023

Problem statement

Given an ArrayList and we have to replace element of it using Java program.

Example:

Input:
55
25
368

Element to replace '25' with  '6'
Output:
55
6
368

Java program to replace element within the ArrayList

import java.util.ArrayList;

public class ExArrayReplace {
  public static void main(String[] args) {
    // Create an object of arrayList. 
    ArrayList arrayList = new ArrayList();

    //Add elements to arraylist.

    arrayList.add("55");
    arrayList.add("25");
    arrayList.add("368");

    System.out.println("Original ArrayList...");

    for (int index = 0; index < arrayList.size(); index++)
      System.out.println(arrayList.get(index));

    // Enter the position and number for replace.
    arrayList.set(1, "6");

    // Print arraylist after replacement.
    System.out.println("ArrayList after replacement...");
    for (int index = 0; index < arrayList.size(); index++)

      System.out.println(arrayList.get(index));
  }
}

Output

The output of the above example is:

Original ArrayList...
55
25
368
ArrayList after replacement...
55
6
368

Java ArrayList Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.