- Vector is like the dynamic array which can grow or shrink its size.
- Vector is similar to ArrayList but threadsafe
- It is recommended to use the Vector class in the thread-safe implementation only else use ArrayList
- Iterator returned by Vector is fail-fast. Means any structural modification made to Vector like adding or removing elements during Iteration will throw java.util.ConcurrentModificationException.
It is similar to the ArrayList, but with two differences-
- Vector is synchronized.
- Java Vector contains many legacy methods that are not the part of a collections framework.
Example :
package java8; import java.util.Vector; public class VectorDemo { public static void main(String[] args) { Vector<String> vec = new Vector<String>(); //Adding elements using add() method of List vec.add("Tiger"); vec.add("Lion"); vec.add("Dog"); vec.add("Elephant"); //Adding elements using addElement() method of Vector vec.addElement("Rat"); vec.addElement("Cat"); vec.addElement("Deer"); System.out.println("Elements are: "+vec); } }
Since it is similar to arraylist, the complexity of Vector is same
Complexity of Vector
Vector | Time Complexity | Space Complexity |
Adding Element | O(1) – resize O(log(n)) | |
Removing Element | O(n) | |
Iterating Elements | O(n) | |
Retreving Element at Position | O(1) |
Reference :
https://www.interviewsansar.com/java-vector-time-complexity-and-how-vector-grows-in-java/