Java Vector

In Java Vector is a class which is available in java.util package. Vector is like dynamic array which can grow or shrink its size. Vector is use to create a resizable array similar to ArrayList. It inherits the AbstractList class and implements List and Deque interfaces.

There are some key points to remember about LinkedList:

  1. Vector is thread-safe.
  2. We can use the vector while working with thread.
  3. Vector implements a dynamic array which means it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index.
  4. Java Vector contains many legacy methods that are not the part of a collections framework.
  5. Vector also maintains an insertion order like an ArrayList. Still, it is rarely used in a non-thread environment as it is synchronized, and due to this, it gives a poor performance in adding, searching, deleting, and updating its elements.
  6. The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification, it fails and throws the ConcurrentModificationException.

Creating a Vector

                        List list = new Vector();
                                (or)
                        Vector vector = new Vector();
                    
Creating an Vector of a specific type

                        // create Integer type Vector
                        Vector<Integer> vector = new Vector<Integer>();

                        // create String type vector
                        Vector<String> vector = new Vector<String>();
                    

In above we have created an Vector of two different types integer and string.

  1. If we create a Vector using Integer type then we can store only Integer type of element.
  2. If we create a Vector using String type then we can store only String type of element.

Vector constructos
Constructor Description Example
Vector() Creates a default vector of the initial capacity is 10. Vector v = new Vector();
Vector(int size) Creates a vector whose initial capacity is specified by size. Vector v = new Vector(int size);
Vector(int size, int incr) Creates a vector whose initial capacity is specified by size and increment is specified by incr. It specifies the number of elements to allocate each time a vector is resized upward. Vector v = new Vector(int size, int incr);
Vector(Collection c) Creates a vector that contains the elements of collection c. Vector v = new Vector(Collection c);
Methods of Vector class

There are some basic commonly used methods are:

Method Name Description
add(element) adds an element to vectors.
add(index, element) adds an element to the specified position.
addAll(vector) adds all elements of a vector to another vector.
get(index) returns an element specified by the index.
iterator() returns an iterator object to sequentially access vector elements.
remove(index) removes an element from specified position.
removeAll() removes all the elements.
clear() removes all elements. It is more efficient than removeAll()
set() changes an element of the vector.
size() returns the size of the vector.
toArray() converts the vector into an array.
toString() converts the vector into a String.
contains() searches the vector for specified element and returns a boolean result.
Basic Operations on Vector

The Vector class provides various methods to perform different operations on vectos. We will look at some commonly used Vector operations.

  1. ▪ Add elements
  2. ▪ Access elements
  3. ▪ Remove elements

Add elements:

To add a single element to the Vector, we use the add(), addAll(index, element), addAll(vector) method of the Vector class. For example,


                        import java.util.Vector;

                        public class VectorAddExample {
                            public static void main(String[] args) {
                                Vector<String> mammals= new Vector<String>();

                                // Using the add() method
                                mammals.add("Dog");
                                mammals.add("Horse");

                                // Using index number
                                mammals.add(2, "Cat");
                                System.out.println("Vector: " + mammals);

                                // Using addAll()
                                Vector<String> animals= new Vector<String>();

                                animals.add("Crocodile");

                                animals.addAll(mammals);
                                System.out.println("New Vector: " + animals);
                            }
                        }

                    
Access elements:

To access elements of a vector we can use get(index), iterator() method of the Vector. For example,


                        import java.util.Iterator;
                        import java.util.Vector;

                        public class VectorAccessExample {
                            public static void main(String[] args) {
                                Vector<String> animals= new Vector<String>();
                                animals.add("Dog");
                                animals.add("Horse");
                                animals.add("Cat");

                                // Using get()
                                String element = animals.get(2);
                                System.out.println("Element at index 2: " + element);

                                // Using iterator()
                                Iterator<String> iterate = animals.iterator();
                                System.out.print("Vector: ");
                                while(iterate.hasNext()) {
                                    System.out.print(iterate.next());
                                    System.out.print(", ");
                                }
                            }
                        }

                    
Remove elements:

The remove(index), removeAll(), clear() methods of the Vector class is used to remove an element from the Vector. For example,


                        import java.util.Vector;

                        public class Main {
                            public static void main(String[] args) {
                                Vector<String> animals= new Vector<String>();
                                animals.add("Dog");
                                animals.add("Horse");
                                animals.add("Cat");

                                System.out.println("Initial Vector: " + animals);

                                // Using remove()
                                String element = animals.remove(1);
                                System.out.println("Removed Element: " + element);
                                System.out.println("New Vector: " + animals);

                                // Using clear()
                                animals.clear();
                                System.out.println("Vector after clear(): " + animals);
                            }
                        }

                    
Differences between ArrayList and Vector:
ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.
ArrayList increments 50% of current array size if the number of elements exceeds from its capacity. Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity.
ArrayList is not a legacy class. It is introduced in JDK 1.2. Vector is a legacy class.
ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object.
ArrayList uses the Iterator interface to traverse the elements. A Vector can use the Iterator interface or Enumeration interface to traverse the elements.