Author
Artem Divertitto
Senior Android Developer at United Tech

Java Vector

Published in the Java Collections group
Probably you've already come across arrays in Java, and you know that one of their main drawbacks is size constancy. Once you've created an array of a certain size, you can't change that later. There are several Java Collection framework classes in the Java language that solve this problem. One of them is Java Vector Class. It will be discussed in this article.

What is Vector Class

As we wrote in the preface, the Vector class from Java Collection Framework eliminates the problem of the static size of arrays. Java Vector is a kind of a dynamic array and can grow or shrink in size. Using the Vector collection class, we can store a group of elements as simple objects and manipulate them through the various methods. The Vector class is available from the java.util package. Thus, Vector in Java can be used if you don't know the size of the array beforehand, or if you need an "array" that can change dimensions over the lifetime of the program. It must be said right away that the Vector class is already quite old, and later collections appeared that can replace it in the vast majority of cases. The popular “analogue” of Java Vector is the ArrayList class. The most important difference between these classes from each other is that Vector is synchronized, while ArrayList isn't. We’ll talk about other differences between these two classes and more modern analogues of the Vector class a little later in the section “What's wrong with the Vector class”.

Java Vector Methods

Here are Java Vector Methods:
  • void add(int index, Object element) inserts the specified element at the specified position of the vector.

  • boolean add(Object o) adds the specified element to the end of the vector.

  • boolean addAll(Collection c) adds all the elements in the specified collection to the end of the vector, in the order that they are returned by the specified collection iterator.

  • boolean addAll(int index, Collection c) inserts all elements within the specified Collection into the vector at the specified position.

  • void addElement(Object obj) adds the specified component to the end of this vector, increasing its size by one.

  • int capacity() returns the current capacity of this vector.

  • void clear() removes all elements from this vector.

  • Object clone() returns a clone of this vector.

  • boolean contains(Object elem) tests whether the specified object is a component in this vector.

  • boolean containsAll(Collection c) returns true if the vector contains all elements of the specified Collection.

  • void copyInto(Object[] anArray) copies the components of this vector to the specified array.

  • Object elementAt(int index) returns the component at the specified index.

  • Enumeration elements() returns an enumeration of the components of this vector.

  • void ensureCapacity(int minCapacity) increases the capacity of this vector, if necessary, to ensure that it can hold at least the number of components given by the minimum capacity argument.

  • boolean equals(Object o) compares the specified object to this vector.

  • Object firstElement() returns the first component (element at index 0) of this vector.

  • Object get(int index) returns the element at the specified position in this vector.

  • int hashCode() returns the hash code value for this vector.

  • int indexOf(Object elem) searches for the first occurrence of the given argument, testing for equality using the equals method.

  • int indexOf(Object elem, int index) searches for the first occurrence of the given argument, starting at index, and testing for equality using the equals method.

  • void insertElementAt(Object obj, int index) inserts the specified object as a component into this vector at the specified index.

  • boolean isEmpty() tests this vector for missing components.

  • Object lastElement() returns the last component of the vector.

  • int lastIndexOf(Object elem) returns the index of the last occurrence of the specified object in this vector.

  • int lastIndexOf(Object elem, int index) searches backwards for the specified object, starting at the specified index, and returns the index to it.

  • Object remove(int index) removes the element at the specified position in this vector.

  • boolean remove(Object o) removes the first occurrence of the specified element in this vector. If the vector does not contain an element, it does not change.

  • boolean removeAll(Collection c) removes all elements from the vector that are contained in the specified Collection.

  • void removeAllElements() removes all components from the vector and sets its size to zero.

  • boolean removeElement(Object obj) removes the first (lowest index) occurrence of the argument from this vector.

  • void removeElementAt(int index) removes an element at index.

  • protected void removeRange(int fromIndex, int toIndex) removes from this List all elements whose index is between fromIndex, inclusive, and toIndex, exclusively.

  • boolean retainAll(Collection c) retains only the elements in the vector that are contained in the specified Collection.

  • Object set(int index, Object element) replaces the element at the specified position in this vector with the specified element.

  • void setElementAt(Object obj, int index) sets the component at the specified index of this vector as the given object.

  • void setSize(int newSize) sets the size of this vector.

  • int size() returns the number of components in this vector.

  • List subList(int fromIndex, int toIndex) returns a representation (view) of the part of this List between fromIndex, inclusive, and toIndex, exclusively.

  • Object[] toArray() returns an array containing all the elements of this vector in the correct order.

  • Object[] toArray(Object[] a) returns an array containing all the elements of this vector in the correct order; the execution type of the returned array is the type of the specified array.

  • String toString() returns a string representation of this vector containing a string representation of each element.

  • void trimToSize() trims the capacity of this vector to the vector's current size.

Java Vector Example


import java.util.Vector;

public class VectorExample {

   public static void main(String[] args) {
       Vector vector = new Vector();
       System.out.println("the size of the empty vector = " +  vector.size());
       //adding some vector elements
       vector.add("Johnny");
       vector.add("Ivy");
       vector.add("Ricky");
       System.out.println(vector); 
       
       //adding more vector elements       
       vector.add("Johnny");
       vector.add("Paul");
       System.out.println(vector);
       System.out.println("the size of the vector = " +  vector.size());
       System.out.println("the first element of the vector = " + vector.firstElement());

       //here the program will print out the first appearance of "Johnny" element
       System.out.println(vector.indexOf("Johnny"));
       //program will print out the first appearance of "Johnny" element starting from the element 1
       System.out.println(vector.indexOf("Johnny", 1));
       vector.clear(); //deleting all vector elements
       System.out.println("the size of the vector after clear method = " +  vector.size());

   }
}
The output of this program is here below:
the size of the empty vector = 0 [Johnny, Ivy, Ricky] [Johnny, Ivy, Ricky, Johnny, Paul] the size of the vector = 5 the first element of the vector = Johnny 0 3 the size of the vector after clear method = 0

What’s wrong with Vector Class?

According to the documentation of Java Vector class, if you don’t need a thread-safe implementation in your program, it is recommended to use ArrayList in place of Vector (Collection Framework more effective participant). Let’s change the example above a little bit, using the ArrayList class instead of Vector.

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {

       public static void main(String[] args) {
           List vector = new ArrayList();
           //Vector vector = new Vector();
           System.out.println("the size of the empty vector = " +  vector.size());
           vector.add("Johnny");
           vector.add("Ivy");
           vector.add("Ricky");
           System.out.println(vector);
           vector.add("Johnny");
           vector.add("Paul");
           System.out.println(vector);
           System.out.println("the size of the vector = " +  vector.size());
           //System.out.println("the first element of the vector = " + vector.firstElement());

           //here the program will print out the first appearance of "Johnny" element
           System.out.println(vector.indexOf("Johnny"));
           //program will print out the first appearance of "Johnny" element starting from the element 1
           //System.out.println(vector.indexOf("Johnny", 1));
           vector.clear();
           System.out.println("the size of the vector after clear method = " +  vector.size());

       }
   }
We commented out the line with vector.indexOf("Johnny", 1), because there’s no such method in this variation in the ArrayList class. For the same reason, the vector.firstElement() line was commented out. In all other respects, the program produces the same result as the first one. Of course, in such an example, it is not clear why ArrayList is better than Vector. This requires more knowledge about, say, threads. We list the reasons here. Firstly, although the Vector class is synchronized, it can’t be called completely thread-safe, although this seems strange. The fact is that Vector synchronizes each operation, not the entire Vector instance itself. This can be a problem in programs where you need to synchronize the entire set of operations rather than individual operations. Say, if one thread is iterating over a vector and another thread is structurally modifying an instance of the vector, the iterator will throw a ConcurrentModificationException. It turns out that two threads can work with a Vector instance at the same time if they perform different operations. Secondly, the Vector class doesn’t have the best performance because its objects have a resizable array and synchronization. This combination means additional overhead for blocking operations, whether synchronization is required or not. Sure, this affects performance. In addition, synchronizing the vector on each operation also has a negative effect on performance, since we’ll acquire a lock again and again for each operation. If the entire instance of the class were synchronized, then the lock would also be acquired once, which is much more efficient. Thirdly, Vector supports some legacy methods. For example elements(). This method returns an enumeration of the components of the vector. Programmers most often use Iterator or ListIterator to Enumeration, and for a number of reasons. In particular, Enumeration does not have a remove() method defined, which means that the list cannot be structurally modified during iteration. Also, unlike ListIterator, Enumeration does not offer bidirectional access. As you can see, Vector has quite a few problems. What if you still need a thread-safe implementation of List interface? In this case, ArrayList won’t help, but you can use, for example, the CopyOnWriteArrayList class instead of Vector; it is positioned as a thread-safe variant of the ArrayList. You can also synchronize ArrayList using the Collections synchronizedList() method.

Vector really has some problems... why is it still in Java and why should it be taught?

The question arises: why are we studying the Vector class at all? And why hasn't it been removed from Java yet? The fact is that Java professes the principle of backward compatibility. This means that all old code written many years ago will be understood by modern versions of Java. In addition, there are quite a few enterprise-level applications in the Java environment that have been supported for decades. It is quite possible that you will have to deal with such a “dinosaur” in your work, so you need to be prepared for surprises, such as code with ineffective legacy classes.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION