Write a Java program to replace a specified element at all places with another element in Vector collection


The code you provided is written in Java and demonstrates the use of the Collections.replaceAll() method to replace specific elements in a Vector with a new value. Here's how the code works:

  • A Vector named vec_list is created to store integer values.
  • Five elements (10, 20, 30, 40, and 50) are added to the vec_list using the add() method.
  • The initial elements in the vec_list are printed using System.out.println().
  • The Collections.replaceAll() method is used to replace all occurrences of the value 30 with 300 in the vec_list.
  • The modified elements in the vec_list are printed again to verify the changes.

Source Code

import java.util.*;
public class Replace_Element
{
	public static void main(String[] args)
	{
		Vector < Integer > vec_list = new Vector < Integer > ();
		vec_list.add(10);
		vec_list.add(20);
		vec_list.add(30);
		vec_list.add(40);
		vec_list.add(50);
		System.out.println("Vector Elements : " + vec_list);
 
		Collections.replaceAll(vec_list, 30, 300);
 
		System.out.println("Vector elements: " + vec_list);
	}
}

Output

Vector Elements : [10, 20, 30, 40, 50]
Vector elements: [10, 20, 300, 40, 50]

Example Programs