DEV Community

Cover image for Vector and Stack Classes
Paul Ngugi
Paul Ngugi

Posted on

Vector and Stack Classes

Vector is a subclass of AbstractList, and Stack is a subclass of Vector in the Java API. The Java Collections Framework was introduced in Java 2. Several data structures were supported earlier, among them the Vector and Stack classes. These classes were redesigned to fit into the Java Collections Framework, but all their old-style methods are retained for
compatibility.

Vector is the same as ArrayList, except that it contains synchronized methods for accessing and modifying the vector. Synchronized methods can prevent data corruption when a vector is accessed and modified by two or more threads concurrently. For the many applications that do not require synchronization, using ArrayList is more efficient than using Vector.

The Vector class extends the AbstractList class. It also has the methods contained in the original Vector class defined prior to Java 2, as shown in Figure below.

Image description

Most of the methods in the Vector class listed in the UML diagram in Figure above are similar to the methods in the List interface. These methods were introduced before the Java Collections Framework. For example, addElement(Object element) is the same as the add(Object element) method, except that the addElement method is synchronized. Use the ArrayList class if you don’t need synchronization. It works much faster than Vector.

The elements() method returns an Enumeration. The Enumeration interface was introduced prior to Java 2 and was superseded by the Iterator interface. Vector is widely used in Java legacy code because it was the Java resizable array implementation before Java 2.

In the Java Collections Framework, Stack is implemented as an extension of Vector, as illustrated in Figure below.

Image description

The Stack class was introduced prior to Java 2. The methods shown in Figure above were used before Java 2. The empty() method is the same as isEmpty(). The peek() method looks at the element at the top of the stack without removing it. The pop() method removes the top element from the stack and returns it. The push(Object element) method adds the specified element to the stack. The search(Object element) method checks whether the specified element is in the stack.

Top comments (0)