What is the vector.size method in Java?

The size method of the Vector class can be used to get the number of components in this vector.


Vector is a growable array of objects. Elements are mapped to an index.


Syntax


public int size();

Code

import java.util.Vector;
class VectorSizeExample {
public static void main( String args[] ) {
// Creating Vector
Vector<Integer> vector = new Vector<>();
System.out.println("Vector is: " + vector);
System.out.println("Vector Size: " + vector.size());
// add elememts
vector.add(1);
vector.add(2);
vector.add(3);
// Print vector
System.out.println("Vector is: " + vector);
System.out.println("Vector Size: " + vector.size());
}
}

Explanation

  • In the code above, we have created an empty Vector object and printed the size of the vector.

  • The empty Vector object’s size is 0 because it doesn’t contain any elements. We then added 3 values 1, 2, 3 using the add method.

  • We again printed the size of the Vector object using the size method. Now the size method returns 3.

Free Resources