Showing posts with label remove element of vector. Show all posts
Showing posts with label remove element of vector. Show all posts

Monday, 25 May 2015

How To Remove Element of Vector

import java.util.Vector;

public class RemoveElement {

    public static void main(String[] args) {
      
        Vector<String> vector = new Vector<String>();
        //add element in vector
        vector.add("cricket");
        vector.add("hockey");
        vector.add("football");
        vector.add("tennish");
      
        // print vector
        System.out.println("Vector = "+vector);
      
      
        /*
         * Removes the element at the specified position
         * in this Vector. Shifts any subsequent elements
         * to the left (subtracts one from their indices).
         * Returns the element that was removed from the
         *  Vector.
         */
        vector.remove(1);
      
        System.out.println("After remove element vector is = "+vector);
               
            }
     
}

Output:

Vector = [cricket, hockey, football, tennish]

After remove element vector is = [cricket, football, tennish]


How to remove all element from vector

We can remove all element of vector using clear() method . clear() removes all element from the list and return empty list.


import java.util.Vector;

public class RemoveAll {
   
    public static void main(String[] args) {
      
        Vector<String> vector = new Vector<String>();
        //add element in vector
        vector.add("cricket");
        vector.add("hockey");
        vector.add("football");
        vector.add("tennish");
      
        // print vector
        System.out.println("Vector is = "+vector);
      
        /*
         * Removes all of the elements from this
         * Vector. The Vector will be empty after
         *  this call returns (unless it throws an
         *   exception).
         */
        vector.clear();
      
        System.out.println("Vector After Clear is = "+vector);
               
    }

}


Output:

Vector is = [cricket, hockey, football, tennish]

Vector After Clear is = []