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.
Submitted by IncludeHelp, on November 01, 2017

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

Program

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

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

Java ArrayList Programs »





Comments and Discussions!










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