Write a Java program to set an element at the specified index in Vector collection


The code you provided is written in Java and demonstrates the use of the setElementAt() method to replace an element at a specific index in a Vector. Here's how the code works:

  • A Vector named vec_list is created to store string values.
  • Five elements ("Red," "Green," "Blue," "Yellow," and "Orange") are added to vec_list using the add() method.
  • The initial elements in vec_list are printed using System.out.println().
  • The setElementAt() method is used to replace the element at index 3 with the string "Pink" in vec_list.
  • The modified elements in vec_list are printed again to verify the change.

Source Code

import java.util.*;
public class SetElement
{
	public static void main(String[] args)
	{
		Vector < String > vec_list = new Vector < String > ();
		vec_list.add("Red");
		vec_list.add("Green");
		vec_list.add("Blue");
		vec_list.add("Yellow");
		vec_list.add("Orange");
 
		System.out.println("Vector Elements : " + vec_list);
 
		vec_list.setElementAt("Pink", 3);
 
		System.out.println("Vector Elements : " + vec_list);
	}
}

Output

Vector Elements : [Red, Green, Blue, Yellow, Orange]
Vector Elements : [Red, Green, Blue, Pink, Orange]

Example Programs