Write a Java program to Replace a particular element in an ArrayList with the given element


This program demonstrates how to replace particular elements in an ArrayList in Java. The ArrayList contains a list of fruits and the program replaces the elements at index 2 and 5 with "Mulberry" and "Guava" respectively. Here's a breakdown of the code:

  • We first import the ArrayList class from the java.util package.
  • We define a class named ReplaceElement_Particular.
  • Inside the class, we create an ArrayList named fru_list and add some fruits to it.
  • We then print the initial ArrayList using the println() method.
  • To replace particular elements in the ArrayList, we use the set() method. We call the set() method twice to replace the elements at index 2 and 5 with "Mulberry" and "Guava" respectively.
  • Finally, we print the updated ArrayList using the println() method.

Source Code

import java.util.ArrayList;
public class ReplaceElement_Particular
{
    public static void main(String[] args)
    {
		ArrayList<String> fru_list = new ArrayList<String>();
		fru_list.add("Pineapple"); 
		fru_list.add("Papaya");
		fru_list.add("Mango");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		fru_list.add("Watermelon");
		System.out.println("Given ArrayList : "+fru_list); 
 
		//Replacing the element at index 2,5 with "Mulberry","Guava" 
		fru_list.set(2, "Mulberry");
		fru_list.set(5, "Guava"); 
		System.out.println("After Replace Element in ArrayList : "+fru_list);
    }
}

Output

Given ArrayList : [Pineapple, Papaya, Mango, Apple, Banana, Cherry, Watermelon]
After Replace Element in ArrayList : [Pineapple, Papaya, Mulberry, Apple, Banana, Guava, Watermelon]

Example Programs