Java Vector clear() Example

The clear() method of java.util.Vector class will remove all the content of the Vector

Signature

public void clear()

This method removes all of the elements from the vector.

Example

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

import java.util.Vector;

public class ClearMethodVectorExample 
{	
	public static void main(String args[])
	{
		// Create vector1 object
		Vector vector1 = new Vector();
						
		//adding elements to Vector using add()
		vector1.add("Element1");
		vector1.add("Element2");
		vector1.add("Element3");
		vector1.add("Element4");
		
		//Printing the elements of the Vector1
        System.out.println("**Elements of the Vector1 before clear**");
        System.out.println("Size of the vector : "+vector1.size());
        for(String val : vector1)
        {
                System.out.println(val);
        }
        
        vector1.clear();
        
        //Printing the elements of the Vector1
        System.out.println("**Elements of the Vector1 after clear**");
        System.out.println("Size of the vector : "+vector1.size());
        for(String val : vector1)
        {
                System.out.println(val);
        }
	}
}

Output

**Elements of the Vector1 before clear**
Size of the vector : 4
Element1
Element2
Element3
Element4
**Elements of the Vector1 after clear**
Size of the vector : 0

Leave a Reply

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