Vector in Java


JavaViews 1569

The Vector in Java is a class that implements a dynamic array. This means we can increase or decrease the size of the array dynamically. It is same like ArrayList in Java but has few differences. In this tutorial, we will understand in detail the Java Vector class, its implementation, and different methods.

Java Vector

The Java Vector class implements the List interface and is part of the legacy classes which means it has its own methods that are not present in the Collection framework. The Java vector class is present in the java.util package. Hence to use the vector class, we need to import the java.util.Vector package.

Java Vector is used to create an array of dynamic size. This means we can increment the size of the array we add the elements after it reaches a specific size. We will understand in detail about this in the next section.

Another feature of the vector is that we can store values of different data types to the same vector object. Suppose we have created a vector object, we can add an integer value first, then a string value, then again an integer, and so on.

Java Vector Constructors

We can declare vector in the below different ways:

ConstructorDescriptionSyntax
Vector()Creates a default vector of capacity 10Vector v = new Vector();
E - Element type
Vector(int size)Creates a vector with capacity specified by the size parameterVector v = new Vector(size);
size - capacity
Vector(int size, int increment)Creates a vector with capacity specified by the size parameter and increases the size by the increment parameter when it reaches the capacityVector v = new Vector(size, inc);
size - capacity
inc - increment value
Vector(Collection c)Creates a vector that contains the elements of CollectionVector v = new Vector(c);
c - collection list

Java Vector Methods

We can use the below methods or operations for a vector class:

MethodDescriptionParameter
Boolean add(Object e)Adds the specified element to the end of the vectore - the element to be added.
Return value - True
void add(int index, Object e)Adds the element to the specified index. If the index already contains an element, it is shifted to the rightindex- the index at which the element needs to be inserted
e - the element which needs to be inserted
Boolean addAll(Collection c)Adds a collection of specified elements to the vectorc - collection of elements to be added
Return value - true
Boolean addAll(int index, Collection c)Adds a collection of elements at the specified index. If the index already contains element, it is subsequently shifted to the rightindex - index at which the elements needs to be added
c - collection of elements to be added
Return value - True
void addElement(Object obj)Adds the specified component to the vectorobj - the component to be added
int capacity()Returns the current capacity or size of the vector
void clear()Removes all elements from the vector and becomes empty
Object clone()Returns a clone of the vector where the copy contains a reference to the clone of the internal data array
Boolean contains(Object o)Checks if the vector contains the specified elementReturn value - true if the list contains the element
Boolean containsAll(Collection c)Checks if the vector contains all the elements in the collectionReturn value - true if the list contains all the elements
void copyInto(Object[] anArray)Copies the contents of the vector into the specified arrayanArray - array that has to hold the content of the vector
Object elementAt(int index)Returns the object at the specified index
Enumeration elements()Returns an enumeration of all the components in the vector where start index is at 0
void ensureCapacity(int minCapacity)Ensures that the vector can hold the least minimum capacity specified
Boolean equals(Object o)Compares if the vector contains all the specified elements in the exact orderReturn value - true if object elements match with the list
Object firstElement()Returns the first component at index 0
void forEach(Consumer action)Performs the given action for the element in the vector in an iteration.
Object get(int index)Returns the element at the specified indexindex - the position of the element to be retrieved
int indexOf(Object o)Fetches the index of the first occurrence of the specified elemento - The element to be identified
Return value - index value
int indexOf(Object o, int index)Returns the index of the first occurence of the element specified starting from the index mentionedo - The element to be identified
index - start index of the search
void insertElementAt(Object o, int index)Inserts the specified object as component to the vector at the specified indexo - The element to be identified
index - index at which element has to be inserted
boolean isEmpty()Checks if the vector is empty
Iterator iterator()Returns an iterator over the elements in the vector
Object lastElement()Returns the last element in the vector
int lastIndex(Object o)Returns the last occurrence of the specified element. If not present, returns -1
int lastIndex(Object o, int index)Returns the last occurrence of the specified element searching backwards from the specified index. If not present, returns -1
ListIterator listiterator()Returns the listiterator over the elements in the vector
ListIterator listiterator(int index)Returns the listiterator over the elements in the vector from the specified index
Object remove(int index)Removes the element at the specified index from the vectorReturn value - the element that is removed
boolean remove(Object o)Removes the specified element from the vectorReturn value - true if removed
Boolean removeAll(Collection c)Removes all the elements of the Collection from the vectorc - Collection elements
void removeAllElements()Removes all components from the vector and sets the size to 0
boolean removeElement(Object o)Removes the specified element from the vectorReturn value - true if removed
void removeElementAt(int index)Removes or deletes the component at the specified index
boolean removeIf(Predicate filter)Removes all elements that satisfies the given predicatefilter - condition to be applied
Boolean retainAll(Collection c)Retains all the elements specified in collection in the vector. Other elements will be removedc - collection of elements that has to be retained
Return value - true if the vector changed due to the method called
Object set(int index, Object o)Replaces the element at the specified index with the object passedo - the element to be replaced
index - index of the element
Return value - Returns the element which was previously at the specified index
void setElementAt(Object o, int index)Sets the component at the specified index by discarding the old valueo - element to be set
index - index at which the element has to be updated
void setSize(int newsize)Sets the size of the vector with the specified valuenewsize - size of the vector
int size()Returns the number of components in the vector
void sort(Comparator c)Sorts the elements in the vector based on the comparatorc - comparator value
List sublist(int fromIndex, int toIndex)Retrieves the part of the list based on start and endIndexfromIndex - position from which the sublist has to be retrieved (included)
toIndex - the index until which the sublist has to be retrieved (excluded)
Object[] toArray()Returns an array of elements in the vector
void trimToSize()Trims the capacity of the vector to be the current capacity size

Example: Different ways to create a vector

Below is an example that shows the different ways of creating a vector using its constructors.

import java.util.Vector;

public class VectorDemo {

  public static void main(String[] args) {
    Vector<Integer> v1 = new Vector<Integer>();
    
    //Adding elements
    v1.add(2);
    v1.add(3);
    
    Vector<String> v2 = new Vector<String>(3);
    Vector<String> v3 = new Vector<String>(4,2);
    Vector<Integer> v4 = new Vector<Integer>(v1);
    
    //Capacity of each vector
    System.out.println("Capacity of v1: " + v1.capacity());
    System.out.println("Capacity of v2: " + v2.capacity());
    System.out.println("Capacity of v3: " + v3.capacity());
    System.out.println("Capacity of v4: " + v4.capacity());

    v3.add("Java");
    v3.add("C");
    v3.add("C++");
    v3.add("Python");
    v3.add("Ruby");
    System.out.println("Capacity of v3 after adding elements: " + v3.capacity());
  }

}
Capacity of v1: 10
Capacity of v2: 3
Capacity of v3: 4
Capacity of v4: 2
Capacity of v3 after adding elements: 6

Example: Add different data types to a vector

Below is an example to show how a vector can contain different data type values. Here we store data types of both Integer and String in the same vector object.

import java.util.Vector;

public class VectorDemo {

  public static void main(String[] args) {
    Vector v = new Vector();
    v.add("Java");
    v.add(100);
    v.add("Language");
    System.out.println(v);
  }

}
[Java, 100, Language]

Example: Add Elements to Vector

The below example shows different ways to add elements to a vector in Java. Using the add() method, we can individual elements in sequential order. The add(element, index) method adds the element at the specified index. The addElement() method adds the element at the end. We can use the addAll(c) method to add a collection of elements.

import java.util.Vector;

public class VectorAddElements {

  public static void main(String[] args) {
    Vector<Integer> num = new Vector<Integer>();
    num.add(10);
    num.add(20);
    System.out.println("List of elements: " + num);
    
    //Add element at specified index
    num.add(1, 15);
    System.out.println("List of elements: " + num);
    
    //Add an element
    num.addElement(25);
    System.out.println("List of elements: " + num);
    
    Vector<Integer> n = new Vector<Integer>();
    n.add(30);
    n.add(35);
    
    //Add a collection to the vector
    num.addAll(3, n);

    System.out.println("List of elements: " + num);
  }

}
List of elements: [10, 20]
List of elements: [10, 15, 20]
List of elements: [10, 15, 20, 25]
List of elements: [10, 15, 20, 30, 35, 25]

Example: Remove elements from the vector

The below example shows different ways to remove elements from the vector. The remove(index) and removeElementAt(index) removes the element at the specified index. We use remove(element) and removeElement(element) to remove the specified element. The removeAllElements() removes all the elements from the vector and empties the vector.

import java.util.Vector;
public class VectorRemoveElements {

  public static void main(String[] args) {
    Vector<String> names = new Vector<String>();
    names.add("Ramya");
    names.add("Kavitha");
    names.add("Sunitha");
    names.add("Devika");
    names.add("Radhika");
    
    System.out.println("Vector elements: " + names);
    
    names.remove(1);
    System.out.println("Elements after removing element at index 1: " + names);
    names.remove("Sunitha");
    System.out.println("Elements after removing the specified element: " + names);
    
    Vector<String> n = new Vector<String>();
    n.add("Ram");
    n.add("Dev");
    n.add("Das");
    n.add("Jay");
    
    names.addAll(n);
    System.out.println("Elements after adding collection: " + names);
    names.removeElement("Dev");
    System.out.println("Elements after removing specified element: " + names);
    names.removeAll(n);
    System.out.println("Elements after removing the collection: " + names);
    names.removeElementAt(1);
    System.out.println("Elements after removing the element at the specified index: " + names);
    names.removeAllElements();
    System.out.println("Elements after removing all elements: " + names);
    System.out.println("Is vector empty: " + names.isEmpty());

  }

}
Vector elements: [Ramya, Kavitha, Sunitha, Devika, Radhika]
Elements after removing element at index 1: [Ramya, Sunitha, Devika, Radhika]
Elements after removing the specified element: [Ramya, Devika, Radhika]
Elements after adding collection: [Ramya, Devika, Radhika, Ram, Dev, Das, Jay]
Elements after removing specified element: [Ramya, Devika, Radhika, Ram, Das, Jay]
Elements after removing the collection: [Ramya, Devika, Radhika]
Elements after removing the element at the specified index: [Ramya, Radhika]
Elements after removing all elements: []
Is vector empty: true

Example: Update and Retrieve elements from a vector

There are different ways to retrieve elements from a vector in Java and its corresponding index. The below example shows how to update the value and retrieve various elements from the vector. We can update the element using the set() method or setElementAt() method.

The elementAt() and get() is used to retrieve the element at the specified index. We use firstElement() to get the first element and lastElement() to get the last element in the vector.

import java.util.Vector;
public class RetrieveVectorElements {

  public static void main(String[] args) {
    Vector v = new Vector();
    v.add("Welcome");
    v.add("to");
    v.add("Java");
    v.add("programming");
    v.add(100);
    
    System.out.println("Vector content:" + v);
    System.out.println("Element at index 2: " + v.elementAt(2));
    System.out.println("First element: " + v.firstElement());
    System.out.println("Element at index 3: " + v.get(3));
    System.out.println("Index of the specified element: " + v.indexOf("Java"));
    System.out.println("Index of the element from the specified index: " + v.indexOf(100, 1));
    System.out.println("Last element: " + v.lastElement());
    System.out.println("Last index of the element: " + v.lastIndexOf("programming"));
    System.out.println("Last index of the element from the specified index: " + v.lastIndexOf("to", 3));
 
    v.set(4,"language");
    v.setElementAt("Python", 2);
    System.out.println("Elements after using set method: " + v);
    
  }

}
Vector content:[Welcome, to, Java, programming, 100]
Element at index 2: Java
First element: Welcome
Element at index 3: programming
Index of the specified element: 2
Index of the element from the specified index: 4
Last element: 100
Last index of the element: 3
Last index of the element from the specified index: 1
Elements after using set method: [Welcome, to, Python, programming, language]

Example: Iterate through elements in a vector

We can iterate through elements in the vector using below different ways:

  • For loop
  • Enhanced for loop
  • Iterator
  • List Iterator

Below example shows how to traverse through the vector using all the above methods.

import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
public class IterateVectorElements {

  public static void main(String[] args) {
    Vector<String> cities = new Vector<String>();
    cities.add("Chennai");
    cities.add("Delhi");
    cities.add("Bangalore");
    cities.add("Hyderabad");
    
    //For loop
    System.out.println("Iteration through for loop");
    for(int i=0;i<cities.size();i++)
      System.out.println(cities.get(i));
    
    //Enhance for loop
    System.out.println("Iteration through enhanced for loop");
    for(String c: cities)
      System.out.println(c);
    
    //Iterator
    System.out.println("Iteration through iterator");
    Iterator<String> it = cities.iterator();
    it.forEachRemaining(System.out::println);
    
    //ListIterator
    System.out.println("Iteration through List Iterator");
    ListIterator<String> lit = cities.listIterator();
    lit.forEachRemaining(System.out::println);

  }

}
Iteration through for loop
Chennai
Delhi
Bangalore
Hyderabad
Iteration through enhanced for loop
Chennai
Delhi
Bangalore
Hyderabad
Iteration through iterator
Chennai
Delhi
Bangalore
Hyderabad
Iteration through List Iterator
Chennai
Delhi
Bangalore
Hyderabad

Example: Empty elements in Vector

In the below example, we can see how to empty the vector using the clear() method. We can also use removeAllElements() method as we saw in the previous example.

import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
public class IterateVectorElements {

  public static void main(String[] args) {
    Vector<String> cities = new Vector<String>();
    cities.add("Chennai");
    cities.add("Delhi");
    cities.add("Bangalore");
    cities.add("Hyderabad");
    
    cities.clear();
    System.out.println("Is vector empty: " + cities.isEmpty());

  }

}
Is vector empty: true

 

Reference

Translate ยป