This example shows how to check if the Vector is empty in Java. This example also shows how to check if the Vector is empty using the isEmpty method and size method.
How to check if Vector is empty in Java?
There are a couple of ways using which we can check as given below.
1. Using the isEmpty method
The Vector isEmpty
method returns true if this vector object does not contain any elements.
1 |
public boolean isEmpty() |
It returns false if there is at least one element in the vector object.
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 CheckIfVectorIsEmpty { public static void main(String[] args) { //this will crate a new and empty vector object Vector<String> vColors = new Vector<String>(); /* * To check if the vector is empty, use the * isEmpty method */ //this will return true as there are no elements in the vector System.out.println("Is vector empty? " + vColors.isEmpty() ); //let's add some elements vColors.add("Black"); vColors.add("Orange"); vColors.add("Yellow"); //this will now return false as there are 3 elements in the vector System.out.println("Is vector empty? " + vColors.isEmpty() ); } } |
Output
1 2 |
Is vector empty? true Is vector empty? false |
2. Using the size method
The Vector size method returns the number of elements contained in this vector object.
1 |
public int size() |
It returns 0 if there are no elements in the vector object.
We can compare the return value of the size
method with 0 to check if the vector object contains any elements or not as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//this will crate a new and empty vector object Vector<String> vColors = new Vector<String>(); //this will return true System.out.println( vColors.size() == 0 ); //let's add some elements vColors.add("Black"); vColors.add("Orange"); vColors.add("Yellow"); //this will now return false System.out.println( vColors.size() == 0 ); |
Output
1 2 |
true false |
Which method should I use to check?
Let’s have a look at the source code of the Vector class for both of these methods.
1 2 3 |
public synchronized int size() { return elementCount; } |
1 2 3 |
public synchronized boolean isEmpty() { return elementCount == 0; } |
As we can see from the source code, both the methods use the same elementCount internal variable. So as far as performance is concerned, there will not be any difference between these methods.
However, using the isEmpty
method makes code more readable and cleaner than getting the size and comparing it with 0 for this purpose.
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