Java | Vector class

05 min read

Vector Class:

  • Defined in java.util package. So, import java.util.Vector;
  • A vector is a collection of elements of type Object.
  • Works like an array but can grow automatically when more capacity is needed.
  • In a vector, any type of Object can be stored. Objects that are instances of a variety of classes can also be stored.


There are 3 basic types of Constructors:

1. Vector v = new Vector( );

A vector of default size 10 is created and its size is doubled, if an object is added when the vector has become full.

2. Vector v = new Vector( 100); //int size

A vector of size 100 is created and its size will be doubled when the vector becomes full.

3. Vector v = new Vector( 100, 10);

The size of the vector, whose initial capacity is 100, will be increased by 10, each time when the vector becomes full. Thus, it is efficient than doubling the capacity each time.



I) Vector<String> V = new Vector <String> ( );

ii)Vector<Computer>v1= new Vector<Computer>( ):

The above statements can also be used to create Vector objects. But in the first case, v can store only String objects and in the second case, v I can store only Computer objects. So, Vector v = new Vector(); will allow us to store any type of object. But this will show 2 warning messages while compiling, as it is deprecated. Still, the program can be executed.


1) get( ) Method

  • Used to retrieve the reference from the Vector.
  • Should typecast the object reference returned by this method, to the type, equivalent to the object type to which this will be assigned. However, in println( ), conversion is implicitly

get(int index) ---> the index of the element to be retrieved from the Vector

2) void add(obj)                             

void addElement(obj)             

  • adds the object reference 'obj' to the vector, after any other existing objects in V & increases the size by 1

3)size( )

  • Gives the number of elements that are occupied by the objects in a vector.
  • Typecast the reference to String. This casting is especially needed when the return value of get( ) is assigned to the object.

4) capacity( )

  • Gives the maximum number of objects, the vector can hold at any instant.


  • Input (stdin)

    Output (stdout)

    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)


    Expected Output


    Compiler Message