This example shows how to get vector size in Java. This example also shows how to get the vector size or length using the size method.
How to get Vector size or Vector length in Java?
The size
method of the Vector class returns the number of elements contained in this vector object.
1 |
public int size() |
It returns an int number that is equal to the number of elements currently stored in this vector object. It returns 0 if the vector does not have any elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Vector; public class GetVectorSizeExample { public static void main(String[] args) { Vector<Integer> vNumbers = new Vector<Integer>(); /* * To get the number of elements contained in * the vector object, use the size method */ //this will return 0 as there are no elements System.out.println( vNumbers.size() ); //add some elements vNumbers.add(1); vNumbers.add(2); vNumbers.add(3); //this will return 3 as there are 3 elements System.out.println( vNumbers.size() ); } } |
Output
1 2 |
0 3 |
We can also use the size
method to check if the Vector object is empty or not. To do that, we need to compare the return value of the size
method with 0. If it is equal to 0 then the vector is empty, otherwise, it is not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Vector; public class GetVectorSizeExample { public static void main(String[] args) { Vector<Integer> vNumbers = new Vector<Integer>(); //this will return true as there are no elements System.out.println( "Is empty? " + (vNumbers.size() == 0) ); //add an element vNumbers.add(1); System.out.println( "Is empty? " + (vNumbers.size() == 0) ); } } |
Output
1 2 |
Is empty? true Is empty? false |
This example is a part of the Vector in Java Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 Vector Documentation