Java Vector remove(Object o) Example

The remove(int index) method of java.util.Vector class will remove the element at the specified position in the Vector. Shifts any subsequent elements to the left, whereas remove(Object o) method will remove the first occurrence of the element from the vector if it is present. If the element is not present then it leaves the vector untouched

Signature

public boolean remove(Object o)

This method removes the first occurrence of the element of the vector and returns true if the removal was successful.

Example

The following example shows the usage of java.util.Vector.remove(o) method.

import java.util.Vector;

public class RemoveObjectVectorExample {
	public static void main(String args[])
	{
		// create an empty Vector
		Vector vector1 = new Vector();
		
		// use add() method to add elements to the Vector
		vector1.add("Element1");
		vector1.add("Element2");
		vector1.add("Element3");
		
		//Printing the elements of the Vector
		System.out.println("**Elements of the Vector before remove**");
		for(String temp:vector1)
		{
			System.out.println(temp);
		}
		
		//Removing the "Element1" from the Vector
		boolean flag = vector1.remove("Element2");
		System.out.println("Is the removal successful ?? "+flag);
		
		//Printing the elements of the Vector
		System.out.println("**Elements of the Vector after remove**");
		for(String temp:vector1)
		{
			System.out.println(temp);
		}
	}
}

Output

**Elements of the Vector before remove**
Element1
Element2
Element3
Is the removal successful ?? true
**Elements of the Vector after remove**
Element1
Element3

Leave a Reply

Your email address will not be published. Required fields are marked *