Skip to content

Vector in Java Tutorial with Examples

Java Vector tutorial with examples will help you understand how to use Vector class in an easy way. The Vector in Java is an implementation of the List interface that grows automatically as we add elements to it.

The Vector class is contained in the java.util package so we have to import the java.util package using the import statement to use the Vector class in the code.

The Vector class was a part of Java 1.0, but in Java 2, the Vector class was rewritten to implement the List interface and thus it became the part of the Java Collection Framework.

Java Vector Tutorial

 

Unlike the ArrayList class in Java, the Vector is synchronized but it comes with a cost. If the application does not need thread safety, it is recommended to use the ArrayList instead of the Vector class to get better performance.

Like the ArrayList, the Vector class is also a dynamic array of objects. It maintains an internal array to store its elements and the size of this array is increased or decreased automatically as needed. The size of this internal array is called the capacity of the Vector.

The size of the internal array is increased automatically by a certain number when the vector size becomes greater than the internal array size. This certain number is called the capacity increment of the Vector.

The Vector elements can be accessed using the index just like an array. The index of the elements starts from 0 and ends at the size of the vector – 1 index.

How to create new objects of the Java Vector class?

The Vector class in Java provides several constructors using which we can create new objects of it. The default constructor creates a new and empty vector object.

The object created this way has a capacity of 10 and a capacity increment of 0.

If you want to specify the initial capacity and capacity increment of the Vector object at the creation time, you can use any of the below given overloaded constructors.

The Vector class also provides an overloaded constructor that accepts a Collection object as an argument.

It creates a new vector object containing all the elements of the specified collection object. The vector object’s capacity, in this case,  will be large enough to hold all the elements of the collection.

Java Vector Methods

The below given are some of the important methods of the Vector class in Java.

How to add elements to Vector using the add, addAll, and addElement methods?

The Vector add method adds the specified element at the end of the vector.

It appends the element at the end and returns true.

Output

The Vector addElement method is similar to the add method and appends the element at the end.

How to insert an element in the Vector at the specified index?

The above given add method appends the given element in the vector object. If you want to insert an element at the specified index, use below given overloaded add method.

It inserts the specified element at the specified index in the vector object and shifts any subsequent elements to the right by adding 1 to their indices.

Output

We can also use the insertElementAt method that is identical to the above given add method in functionality.

Notice the difference in the parameter order between these two methods.

How to add all elements of a Collection to the Vector using the addAll method?

The Vector addAll method appends all elements of the specified collection to this vector object.

It returns true if the vector object was changed as a result of this method call.

Output

If you want to insert the collection elements at the specific index instead of at the end, you can use below given overloaded addAll method.

It inserts all the collection elements at the given index in vector and shifts the subsequent elements to the right.

How to get elements from the Vector?

How to get an element at the specific Vector index using the get and elementAt methods?

The Vector get method returns an element located at the specified index.

Output

The Vector elementAt method is identical to the get method in functionality.

Both of these methods throw ArrayIndexOutOfBoundsException if the specified index is out of the range.

How to get the first and last elements from the Vector?

The Vector firstElement method returns the first element of the Vector while the lastElement method returns the last.

Both of these methods throw NoSuchElementException if the vector object is empty. Make sure to check the size of the Vector before calling these methods to avoid this exception.

Output

How to replace an element at the specific index of the Vector using the set and setElementAt methods?

The Vector set method replaces an old element with the given new element at the specified index of the vector object.

It returns the old element that was replaced.

Output

The Vector setElementAt method is identical to the set method in functionality.

Please note the change in the order of the parameters. Plus, the set method returns the previous element located at the specified index, while the return type of the setElementAt method is void.

How to get the size of the Vector using the size method?

The Vector size method returns the number of elements stored in the vector object.

Output

How to set the size of the Vector using the setSize method?

The Vector setSize method sets the size of this vector object.

If the specified new size is greater than the current size of this vector object, null elements are added at the end of this vector object. If the specified new size is less than the size of the vector object, elements having an index greater than or equal to the new size are discarded.

Output

Tip: We can use the setSize method to remove all elements from the vector by passing 0 to it.

How to check if the Vector is empty using the isEmpty method?

The Vector isEmpty method returns true if there are no elements in this vector object.

It returns false if there is at least one element in the vector object.

Output

How to remove elements from the Vector?

How to remove an element from a specific index of Vector using the remove and removeElementAt methods?

The Vector remove method removes the element located at the specified index from the vector object.

It removes the element from the specified index of the vector, shifts the subsequent elements to the left and returns the removed element.

Output

The removeElementAt method is identical to this method in functionality.

However, the return type of this method is void while the remove method returns the element that was removed.

Both of these methods throw ArrayIndexOutOfBoundsException exception if the specified index is out of the range.

How to remove a specific element object from Vector using the remove and removeElement methods?

The overloaded remove method removes the specified element from the vector.

It removes the first occurrence of the specified object from the vector, shifts the subsequent elements to the left and returns true if the element is found. It returns false if the element is not found in the vector.

Output

The removeElement method is identical to this method in functionality.

Note: If the Vector contains the objects of a custom class, then the custom class must override the equals and hashCode methods for these methods to find and remove elements.

How to clear or remove all elements from Vector using the clear and removeAllElements methods?

The Vector clear method removes all elements from the vector object.

The vector object becomes empty after this method call.

Output

The removeAllElements method is similar to the clear method in functionality.

How to remove all elements from Vector that are not contained in a collection using the retainAll method?

The Vector retainAll method retains all the elements in the vector that are also contained in the specified collection object. The rest of the elements are removed from this vector object.

In other words, it is an intersection between this vector object and the specified collection object. Only matching elements between these two objects are retained in the vector, non-matching elements will be removed.

The retainAll method returns true if this vector object is changed due to this method call, false otherwise.

Output

How to find the index of an element using the indexOf and lastIndexOf methods?

How to find the index of the first occurrence of the element?

The Vector indexOf method returns the index of the first occurrence of the specified element in the vector.

It returns -1 if the specified object element is not found in the vector.

Output

The above given indexOf method starts searching for the specified element from index 0. If you want to search for the element from the specified index instead of the 0, you can use the below given overloaded indexOf method.

It will return an index of the first occurrence of the specified object element from the given index.

Output

This method throws IndexOutOfBoundsException if the specified index is negative.

Note: If the Vector contains the objects of a custom class, then the custom class must override the equals and hashCode methods for these methods to work.

How to find the index of the last occurrence of the element?

The Vector lastIndexOf method returns an index of the last occurrence of the specified element in the vector object.

It returns -1 if the specified object element is not found in the vector.

Output

If you want to search for the last occurrence of the element from the given index, use the overloaded lastIndexOf method.

This method searches for the last occurrence of the specified element starting from the given index searching in a backward direction.

Output

This method throws IndexOutOfBoundsException if the specified index greater than or equal to the size of the vector.

Note: If the Vector contains the objects of a custom class, then the custom class must override the equals and hashCode methods for these methods to work.

How to check if element exists in Vector using the contains method?

The Vector contains method returns true if the specified element exists in this vector object.

It returns false if the vector does not contain the specified element.

Output

Note: If the Vector contains the objects of a custom class, then the custom class must override the equals and hashCode methods for the contains method to work properly.

How to check if the Vector contains all elements of a collection using the containsAll method?

The Vector containsAll method returns true if all elements of the specified collection are also present in this vector object.

It returns true if this vector object contains all the elements of the specified collection object, false otherwise.

Output

How to iterate Vector?

There are several ways using which we can iterate over vector elements as given below.

Using Enumeration

Output

Using Iterator

Output

Using ListIterator

Output

Using for loop

Output

Using enhanced for loop

Output

Using forEach (Java version 8 and later)

Output

How to iterate Vector in reverse direction (backward direction)?

Output

How to get a sublist from the Vector using the subList method?

The Vector subList method returns a view of part of this vector object whose elements are between the specified start and end index.

The fromIndex is inclusive while the toIndex is exclusive.

Output

The sublist returned from this method is backed by the original vector object so any changes you make to the sublist will also be reflected in the original vector object, and vice versa.

Output

The subList method throws IndexOutOfBoundsException if the start index is less than 0 or the end index is greater than the vector size. It also throws IllegalArgumentException if the end index is greater than the start index.

How to convert a Vector to an array using the toArray method?

The Vector toArray method returns an array containing all the elements of the vector.

Output

Tip: If the array specified in the toArray method is large enough to hold all the vector elements, the same array is filled with the vector elements and returned. The array element immediately after the vector elements is set to null to indicate the end of the vector elements.

If the specified array is smaller than the size of the vector, then a new array is allocated, filled with vector elements, and returned.

Always try to specify the array of at least the same size as the vector to avoid the allocation of a new array.

How to clone a Vector object using the clone method?

The Vector clone method returns a shallow copy of this vector object.

Output

Please note that the clone method copies only references of the vector elements, not the actual objects. The element references in the cloned vector object still refer to the same element objects.

To understand this, let’s see an example.

Output

As we can see from the output when we change the actual element object, the change is reflected in both vector objects i.e. original as well as cloned object.

What is a Vector capacity and how to manage it?

The Vector is a dynamic array implementation that grows automatically as and when we add more elements to it. It maintains an internal array to store its elements and the size of this internal array is called the capacity of the vector.

To know the current capacity of the vector object, use the capacity method.

The default initial capacity of the Vector object is 10. However, we can use the overloaded constructors to specify the custom initial capacity when we create objects of it.

The Vector class in Java automatically increases the size of this internal array when it is no more sufficient to hold the number of elements we want to add. It does this by allocating a new array with the bigger size and copying the existing elements to the new array. This is a costly operation in terms of performance.

Now suppose we want to add thousand of elements to the vector one by one. So the capacity of the internal array needs to be increased many times to accommodate the new elements. This could impact the performance of the application. If we know approximately how many elements we want to add to vector, we can allocate that much capacity beforehand to avoid this performance penalty.

This can be done in two ways, either at the creation time using the constructor that accepts custom capacity or by using the ensureCapacity method.

This method increases the vector capacity (i.e. the size of the internal array), if required, to hold at least the specified number of elements.

Once the vector capacity is increased, it is not reduced automatically even if you remove the elements from it. If we do not need the increased capacity anymore, we can use the trimToSize method to reduce its capacity to free up the storage space.

This method reduces the capacity of the vector object to the current size of the vector object.

Below given additional Java Vector examples will help you understand Vector concepts in more detail.

Java Vector Examples

References:
Java 8 Vector Documentation

Please let me know if you liked the Java Vector tutorial with examples in the comments section below.

About the author

Leave a Reply

Your email address will not be published.