Write a Java program to remove range on elements from Vector collection based on specified indices


The code is written in Java and demonstrates the usage of the Vector class by extending it in a custom class called "Main". It also shows how to remove a range of elements from the vector. Let's break down the code step by step:

  • The code starts with the import statement, which includes the required packages for the code to run successfully.
  • The class "Main" is defined, which extends the Vector class. By extending Vector, the "Main" class inherits all the methods and properties of the Vector class.
  • Inside the main method, an object of the "Main" class called "vec_list" is created. Since "Main" extends Vector, it can be used as a Vector object.
  • Several strings are added to the "vec_list" object using the add method. These strings are "Red", "Green", "Blue", "Yellow", and "Orange".
  • The line System.out.println("Vector Elements : " + vec_list); prints the elements of the vector to the console, displaying all the strings added to the vector.
  • The line vec_list.removeRange(0, 2); removes a range of elements from the vector. In this case, it removes elements starting from index 0 up to index 2 (inclusive). This means the elements "Red", "Green", and "Blue" are removed from the vector.
  • Finally, the line System.out.println("Vector Elements : " + vec_list); is executed again to print the updated elements of the vector to the console. After removing the range of elements, the vector now contains "Yellow" and "Orange".

Source Code

import java.util.*;
public class Main extends Vector < String >
{
	public static void main(String[] args)
	{
		Main vec_list = new Main();
		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.removeRange(0, 2);
 
		System.out.println("Vector Elements : " + vec_list);
	}
}

Output

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

Example Programs