Java Vector class

The java.util.Vector class is a legacy class in the Collections framework. It basically implements a growable array of objects. Vector extends AbstractList class and implements List Interface.

It is similar to ArrayList class, but with two differences −

1. It is rarely used in non-threaded environment as it is synchronized and due to which it gives poor performance in terms of search, addition, deletion and updation operations on its elements.

2. It contains many legacy methods that are not part of the Java Collections Framework.

Vector proves to be very useful if we don’t know the size of the array in advance or we just need one collection that can change its size dynamically over the lifespan of a program.

 

Vector Class Constructors

Following is the list of constructors provided by the Java Vector class.

Sl. No.

Constructor and Its Description

1

Vector( )

This constructor creates a default vector, which has an initial size of 10.

2

Vector (int size)

This constructor accepts an argument that equals to the required size, and creates a vector whose initial capacity is specified by size.

3

Vector (int size, int incr)

This constructor creates a vector whose initial capacity is specified by size and whose increment is specified by incr. The increment specifies the number of elements to allocate each time that a vector is resized upward.

4

Vector (Collection c)

This constructor creates a vector that contains the elements of collection c.

 

Vector Class Methods

Apart from the methods inherited from its super classes and super interfaces, Vector defines the following methods −

Sl. No.

Method and Its Description

1

void add (int index, Object element)

Inserts the specified element at the specified position in this Vector.

2

boolean add (Object o)

Appends the specified element to the end of this Vector.

3

boolean addAll (Collection c)

Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection’s Iterator.

4

boolean addAll (int index, Collection c)

Inserts all of the elements in in the specified Collection into this Vector at the specified position.

5

void addElement (Object obj)

Adds the specified component to the end of this vector, increasing its size by one.

6

int capacity()

Returns the current capacity of this vector.

7

void clear()

Removes all of the elements from this vector.

8

Object clone()

Returns a clone of this vector.

9

boolean contains (Object elem)

Tests if the specified object is a component in this vector.

10

boolean containsAll (Collection c)

Returns true if this vector contains all of the elements in the specified Collection.

11

void copyInto (Object[] anArray)

Copies the components of this vector into the specified array.

12

Object elementAt (int index)

Returns the component at the specified index.

13

Enumeration elements()

Returns an enumeration of the components of this vector.

14

void ensureCapacity (int minCapacity)

Increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.

15

boolean equals (Object o)

Compares the specified Object with this vector for equality.

16

Object firstElement()

Returns the first component (the item at index 0) of this vector.

17

Object get (int index)

Returns the element at the specified position in this vector.

18

int hashCode()

Returns the hash code value for this vector.

19

int indexOf (Object elem)

Searches for the first occurence of the given argument, testing for equality using the equals method.

20

int indexOf  (Object elem, int index)

Searches for the first occurence of the given argument, beginning the search at index, and testing for equality using the equals method.

21

void insertElementAt (Object obj, int index)

Inserts the specified object as a component in this vector at the specified index.

22

boolean isEmpty()

Tests if this vector has no components.

23

Object lastElement()

Returns the last component of the vector.

24

int lastIndexOf (Object elem)

Returns the index of the last occurrence of the specified object in this vector.

25

int lastIndexOf (Object elem, int index)

Searches backwards for the specified object, starting from the specified index, and returns an index to it.

26

Object remove (int index)

Removes the element at the specified position in this vector.

27

boolean remove (Object o)

Removes the first occurrence of the specified element in this vector, If the vector does not contain the element, it is unchanged.

28

boolean removeAll (Collection c)

Removes from this vector all of its elements that are contained in the specified Collection.

29

void removeAllElements()

Removes all components from this vector and sets its size to zero.

30

boolean removeElement (Object obj)

Removes the first (lowest-indexed) occurrence of the argument from this vector.

31

void removeElementAt (int index)

removeElementAt(int index).

32

protected void removeRange (int fromIndex, int toIndex)

Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive.

33

boolean retainAll (Collection c)

Retains only the elements in this vector that are contained in the specified Collection.

34

Object set (int index, Object element)

Replaces the element at the specified position in this vector with the specified element.

35

void setElementAt (Object obj, int index)

Sets the component at the specified index of this vector to be the specified object.

36

void setSize (int newSize)

Sets the size of this vector.

37

int size()

Returns the number of components in this vector.

38

List subList (int fromIndex, int toIndex)

Returns a view of the portion of this List between fromIndex, inclusive, and toIndex, exclusive.

39

Object[] toArray()

Returns an array containing all of the elements in this vector in the correct order.

40

Object[] toArray (Object[] a)

Returns an array containing all of the elements in this vector in the correct order; the runtime type of the returned array is that of the specified array.

41

String toString()

Returns a string representation of this vector, containing the String representation of each element.

42

void trimToSize()

Trims the capacity of this vector to be the vector’s current size.

Besides these, Vector class defines three protected data members:

  • int capacityIncreament: It indicates the amount by which the capacity of the Vector is automatically incremented when its size becomes greater than its capacity.
  • int elementCount: It denotes the number number of valid components in this Vector object.
  • Object elementData[ ]: It indicates the array buffer into which the components of the Vector are stored.

 

Example 1

The following example shows the use of different constructors of Vector class. It also demonstrates that if increment is specified, Vector will expand according to it in each allocation cycle but if increment is not specified then vector’s capacity get doubled in each allocation cycle. Methods like size(), capacity() and add() are also used here.

VectorDemo1.java

import java.util.Vector;

public class VectorDemo1 {

public static void main(String[] args) {
// Use of constructor 1
Vector v1 = new Vector();
for (int i = 10; i <= 90; i = i + 10) {
v1.add(new Integer(i));
}
System.out.println("Vector1 = " + v1);
System.out.println("Size = " + v1.size());
System.out.println("Capacity = " + v1.capacity());
System.out.println();

// Use of constructor 2
Vector v2 = new Vector(8);
for (double i = 11.11; i <= 99.99; i = i + 11.11) {
v2.add(i); //autoboxing: "add(i)" is equivalent to "new Double(i)"
}
System.out.println("Vector2 = " + v2);
System.out.println("Size = " + v2.size());
System.out.println("Capacity = " + v2.capacity());
System.out.println();

// Use of constructor 3
Vector v3 = new Vector(5, 3);
for (int i = 11; i <= 99; i = i + 11) {
v3.add(i); //autoboxing: "add(i)" is equivalent to "new Integer(i)"
}
System.out.println("Vector3 = " + v3);
System.out.println("Size = " + v3.size());
System.out.println("Capacity = " + v3.capacity());
System.out.println();

// Vector object created using Generics concept
Vector<String> list = new Vector<String>();
list.add("hello");
list.add("hi");
list.add("bye");

// Use of constructor 4
Vector v4 = new Vector(list);
System.out.println("Vector4 = " + v4);
System.out.println("Size = " + v4.size());
System.out.println("Capacity = " + v4.capacity());
v4.add("thanks");
v4.add("welcome");
System.out.println("Vector4 modified = " + v4);
System.out.println("Size = " + v4.size());
System.out.println("Capacity = " + v4.capacity());
System.out.println();
}
}

Output:

Vector1 = [10, 20, 30, 40, 50, 60, 70, 80, 90]
Size = 9
Capacity = 10

Vector2 = [11.11, 22.22, 33.33, 44.44, 55.55, 66.66, 77.77, 88.88, 99.99]
Size = 9
Capacity = 16

Vector3 = [11, 22, 33, 44, 55, 66, 77, 88, 99]
Size = 9
Capacity = 11

Vector4 = [hello, hi, bye]
Size = 3
Capacity = 3
Vector4 modified = [hello, hi, bye, thanks, welcome]
Size = 5
Capacity = 6

 

Example 2

The following example demonstrates the use of different methods of Vector class mainly for addition or insertion operations. It also shows how to enumerate and iterate through the different elements of Vector.

VectorDemo2.java

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

public class VectorDemo2 {

public static void main(String[] args) {
// Creating a Vector of diffrent data types
Vector v = new Vector();
System.out.println("Vector = " + v);
System.out.println("Size = " + v.size());
System.out.println("Capacity = " + v.capacity());

for (int i = 1; i < 10; i++) {
v.add(new Integer(i * 11)); //same as v.add(i*11)
}
v.add("ASIA");
System.out.println("\nVector = " + v);
System.out.println("Size = " + v.size());
System.out.println("Capacity = " + v.capacity());

v.add(0, new Double(99.99)); //same as v.add(0, 99.99)
v.addElement("AUSTRALIA");
v.insertElementAt("EUROPE", 11);
System.out.println("\nVector = " + v);
System.out.println("Size = " + v.size());
System.out.println("Capacity = " + v.capacity());

Object arr[] = v.toArray();
// Accessing elements of the Object array
System.out.println("\nObject array elements are : ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("\n");

System.out.println("Vector = " + v);
System.out.println("Size = " + v.size());
System.out.println("Capacity = " + v.capacity());

// Accessing elements of Vector using get() method
System.out.println("\nVector elements are : ");
for (int i = 0; i < v.size(); i++) {
System.out.print(v.get(i) + " ");
}
System.out.println();

System.out.println("\nVector elements are : ");
// Iterate through the elements of Vector
Iterator it = v.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();

System.out.println("\nVector elements are : ");
// Enumerate through the elements of Vector
Enumeration e = v.elements();
while (e.hasMoreElements()) {
System.out.print(e.nextElement() + " ");
}
System.out.println();

// Remove all elements of Vector
v.removeAll(v);
System.out.println("\nVector = " + v);
System.out.println("Size = " + v.size());
System.out.println("Capacity = " + v.capacity());
}
}

Output:

Vector = []
Size = 0
Capacity = 10

Vector = [11, 22, 33, 44, 55, 66, 77, 88, 99, ASIA]
Size = 10
Capacity = 10

Vector = [99.99, 11, 22, 33, 44, 55, 66, 77, 88, 99, ASIA, EUROPE, AUSTRALIA]
Size = 13
Capacity = 20

Object array elements are :
99.99 11 22 33 44 55 66 77 88 99 ASIA EUROPE AUSTRALIA

Vector = [99.99, 11, 22, 33, 44, 55, 66, 77, 88, 99, ASIA, EUROPE, AUSTRALIA]
Size = 13
Capacity = 20

Vector elements are :
99.99 11 22 33 44 55 66 77 88 99 ASIA EUROPE AUSTRALIA

Vector elements are :
99.99 11 22 33 44 55 66 77 88 99 ASIA EUROPE AUSTRALIA

Vector elements are :
99.99 11 22 33 44 55 66 77 88 99 ASIA EUROPE AUSTRALIA

Vector = []
Size = 0
Capacity = 20

 

Example 3

The following example demonstrates the use of different methods of Vector class mainly for deletion or removal operations. It also shows how to use the ensureCapacity() method of Vector.

VectorDemo3.java

import java.util.Vector;

public class VectorDemo3 {

public static void main(String[] args) {
// Creating a Vector of type String using Java SE 8 style
Vector<String> list = new Vector<>();

// Adding elements to the Vector
list.add("JAVA");
list.add("IS");
list.add("THE");
list.add("BEST");
list.add("LANGUAGE");
list.add(4, "PROGRAMMING");
System.out.println("Vector = " + list);
System.out.println("Size = " + list.size());
System.out.println("Capacity = " + list.capacity());

// Ensuring capacity
list.ensureCapacity(25);
System.out.println("\nNew Capacity = " + list.capacity());

// Copying Vector elements using copyInto() method
Object obj[] = new Object[list.size()];
list.copyInto(obj);
System.out.println("\nElements from Object array: ");
System.out.println("==========================");
for (int i = 0; i < obj.length; i++) {
System.out.print(obj[i] + " ");
}
System.out.println();

// Copying Vector elements using toArray() method
String[] strObj = new String[list.size()];
strObj = (String[])list.toArray(strObj);
System.out.println("\nElements from String array: ");
System.out.println("==========================");
list.forEach(System.out::println);

if (list.contains("BEST")) {
System.out.println("\nBEST is present at the index " + list.indexOf("BEST"));
}
else {
System.out.println("\nBEST is not present in the list.");
}

// Get the first element
System.out.println("\nThe first elementl of vector is = " + list.firstElement());
// Get the last element
System.out.println("\nThe last lement of vector is = " + list.lastElement());

// Using remove()
String element = list.remove(4);
System.out.println("\nRemoved Element: " + element);
System.out.println("Vector after remove(): " + list);

// Remove an element
list.removeElement("IS");
System.out.println("\nVector after removeElement(): " + list);

// Using clear()
list.clear();
System.out.println("\nVector after clear(): " + list);
}
}

Output:

Vector = [JAVA, IS, THE, BEST, PROGRAMMING, LANGUAGE]
Size = 6
Capacity = 10

New Capacity = 25

Elements from Object array:
==========================
JAVA IS THE BEST PROGRAMMING LANGUAGE

Elements from String array:
==========================
JAVA
IS
THE
BEST
PROGRAMMING
LANGUAGE

BEST is present at the index 3

The first elementl of vector is = JAVA

The last lement of vector is = LANGUAGE

Removed Element: PROGRAMMING
Vector after remove(): [JAVA, IS, THE, BEST, LANGUAGE]

Vector after removeElement(): [JAVA, THE, BEST, LANGUAGE]

Vector after clear(): []