beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Remove all elements from Vector in Java – Example

By Chaitanya Singh | Filed Under: Java Collections

In this example, we will see how to remove all the elements from a Vector. We will be using clear() method of Vector class to do this.
public void clear(): Removes all of the elements from this Vector. The Vector will be empty after this method call.

Example

Here we are displaying the size of the Vector before and after calling clear() method. The steps are as follows:
1) Create a Vector.
2) Add elements to it.
3) Call clear() method to remove all the elements.

import java.util.Vector;
public class RemoveAll {
 public static void main(String[] args) {
 
    // Creating a Vector of Strings
    Vector<String> vector = new Vector<String>();
 
    //Adding elements to the Vector
    vector.add("C++");
    vector.add("Java");
    vector.add("Cobol");
    vector.add("C");
    vector.add("Oracle");

    System.out.println("Current size of Vector: "+vector.size());
 
    // Calling clear() method of Vector API
    vector.clear();
 
    System.out.println("Size of Vector after clear(): "+vector.size());
 }
}

Output:

Current size of Vector: 5
Size of Vector after clear(): 0

Enjoyed this post? Try these related posts

  1. Java ArrayList get() Method example
  2. Vector in Java
  3. Deque Interface in Java Collections
  4. How to synchronize HashMap in Java with example
  5. How to get sublist of an ArrayList with example
  6. How to swap two elements in an ArrayList

Leave a Reply Cancel reply

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

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap