In JAVA Collections series, today we will talk about Vector.

The java.util.Vector class implements a growable array of objects. Similar to an Array, which contains components that can be accessed using an integer index.

Following are the important points about Vector − The size of a Vector can grow or shrink as needed to accommodate adding and removing items.

Benefit of Vector

  • Vectors are dynamically-allocated
  • They are not declared to contain a type of variable
  • Each Vector contains a dynamic list of references to other objects
  • Vector stores pointers to the objects
  • Memory-efficient way of handling lists whose size could change drastically

Vector Constructors

1.vector()
2.vector(int initialCapacity, int capacityIncrement)
3.vector(int initialCapacity)
4. Vector( Collection<? extends E> c)

Java Vector class Declaration

  • public class Vector
  • extends Object
  • implements List, Cloneable, Serializable

Example of Vector program

Simple Vector declaration

import java.util.*;  
public class SiriusQVectorExample {  
       public static void main(String args[]) {  
          //Demonstration of Creating a vector  
          Vector<String> vector = new Vector<String>();  
          //Adding elements using add() method of List  
          vector.add("BlogPost1");  
          vector.add("BlogPost2");  
          vector.add("BlogPost3");  
          vector.add("BlogPost4");  
//Demonstration of Adding elements using addElement() method of Vector  
          vector.addElement("JavaPost1");  
          vector.addElement("JavaPost2");  
          vector.addElement("JavaPost3");  
            
          System.out.println("All the Elements are: "+ vector);  
       }  
}  
import java.util.Vector;

class Main {
    public static void main(String[] args) {
        Vector<String> mammals= new Vector<>();

        // Demonstration of Using the add() method
        mammals.add("Lion");
        mammals.add("elephant");

        // Demonstration of Using index number
        mammals.add(2, "Rabbit");
        System.out.println("display of Vector: " + mammals);

        // Demonstration  of Using addAll()
        Vector<String> animals = new Vector<>();
        animals.add("Crocodile");

        animals.addAll(mammals);
        System.out.println("New Vector: " + animals);
    }
}

Leave a Reply

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

Copy link