How to use Vector in Java
Hello everyone, in this article we are going to explore the concept of Vector collection in Java programming language with the help of examples for better understanding.Let's begin
Vector is one of the dynamic arrays in Java to store and organise the data within collections. Vector is derived from Collections and it provides flexible way to classic arrays in Java. Vector is one of the core collection for thread safe implementations.
We need to consider thread-safe operations are reducing the performance. Because of locking/unlocking mechanism. So please consider this difference when thread-safe is not required.
Below you can see an example of initialising of Vector class. We can initialise a vector with initial capacity or we can create directly.
import java.util.*;
class VectorExample {
public static void main(String[] args) {
//Initialize a Vector
Vector<String> vec = new Vector<>();
//Initialize vector with initial capacity
Vector<String> vector = new Vector<>(10);
}
}
We can use add, remove and get methods for organising the data within Vector.
import java.util.*;
class VectorExample {
public static void main(String[] args) {
//Initialize a Vector
Vector<String> vec = new Vector<>(5);
//Insert new data with add method
vec.add("red");
vec.add("green");
vec.add("blue");
// We can get elemen at specific index by get method.
String str = vec.get(0);
System.out.println(str); //red
// We can remove element with specific index
vec.remove(0);
// We can remove element by the value. This will remove first occurance
vec.removeElement("green");
// We can get the number of element with size
int size = vec.size(); //1
// We can get the capacity with capacity method
int capacity = vec.capacity(); //5
System.out.println(size);
System.out.println(capacity);
}
}
Program output will be like below
red
1
5
We can iterate the a vector with traditional for loop, with help of iterator and java streams. Below you can see the examples of iterating a Vector.
import java.util.*;
class VectorExample {
public static void main(String[] args) {
//Initialize a Vector
Vector<String> vec = new Vector<>();
vec.add("the");
vec.add("code");
vec.add("program");
for(String val: vec){
System.out.println(val);
}
Iterator<String> it = vec.iterator();
while (it.hasNext()) {
String val = it.next();
System.out.println(val);
}
vec.stream().forEach(val -> {
System.out.println(val);
});
}
}
As you can see we have iterated the vector in three different ways.
Conclusion
Vectors are providing the to store and organise data, one of main benefit of Vectors is they are suitable at thread safe operations as they are synchronised. But for sure thread-safety comes with some performance loss. If you do not need thread-safety you may also consider to use ArrayList for better performance.
That is all.
Burak Hamdi TUFAN
Comments