Get Vector Size or Length in Java Example

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

publicintsize()

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

importjava.util.Vector;

publicclassGetVectorSizeExample{

publicstaticvoidmain(String[]args){

Vector<Integer>vNumbers=newVector<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.

About the author

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.