Vector Class and the Stack Class in Java Collections

Introduction

Java Collections Framework provides a robust set of classes and interfaces to handle and manipulate collections of objects. Among these, the Vector and Stack classes offer essential functionalities for storing and managing elements in a sequential manner. Both classes are part of the legacy collections but remain relevant due to their synchronized nature and specific use cases. The Vector class implements a dynamic array that can grow or shrink as needed to accommodate the addition and removal of elements. It supports operations such as adding, accessing, and removing elements at specified positions, making it suitable for scenarios where thread safety and ordered traversal are critical. On the other hand, the Stack class extends Vector to represent a last-in, first-out (LIFO) stack of objects. It includes additional methods like push and pop to facilitate stack operations, making it ideal for applications requiring depth-first search traversal, undo mechanisms, or expression evaluation. This Article explores the implementation details, usage scenarios, and comparative analysis of the Vector and Stack classes within the Java Collections Framework. By understanding their capabilities and nuances, developers can leverage these classes effectively to enhance the efficiency and functionality of their Java applications.

The Vector Class

The Vector class in Java extends the AbstractList class and implements key interfaces like List, Cloneable, and Serializable. It serves as a dynamic array similar to ArrayList but with built-in synchronization. This synchronization ensures that only one thread can access a Vector object at a time, making it thread-safe for concurrent operations. This characteristic is particularly useful in scenarios where data integrity across multiple threads is crucial. By implementing synchronized access, the Vector class provides a reliable solution for managing ordered collections in Java applications.

The constructor of the Vector class is,

  • Vector(): This default constructor initializes a Vector with an initial capacity of 10 elements.
  • Vector(int size): Constructs a Vector with the specified initial size.
  • Vector(int size, int increment): Constructs a Vector with the specified initial size. The increment parameter determines how much the Vector's capacity should increase when it needs to expand. If increment is not specified, the Vector doubles its capacity with each expansion.
  • Vector(Collection c): Constructs a Vector containing all elements from the specified Collection c.

These constructors provide flexibility in initializing and populating Vector instances in Java, catering to different needs such as specific initial sizes or copying elements from existing collections.

Methods of Vector Class

  • addElement(Object element): Appends the specified element to the end of the Vector, increasing its size by one.
  • capacity(): Returns the current capacity of the Vector.
  • contains(Object element): Returns true if the Vector contains the specified element.
  • containsAll(Collection c): Returns true if the Vector contains all elements in the specified Collection c.
  • elementAt(int index): Returns the element at the specified index in the Vector.
  • ensureCapacity(int minimumCapacity): Ensures that the Vector has at least the specified minimumCapacity. If the current capacity of the Vector is less than the minimum capacity, it increases its capacity.
  • get(int index): Returns the element at the specified index in the Vector.
  • setElementAt(Object element, int index): Sets the element at the specified index in the Vector to the given element.
  • setSize(int newSize): Sets the size of the Vector to the specified newSize. If newSize is greater than the current size, the Vector is extended with null elements appended; if newSize is less than the current size, all components at index newSize and greater are discarded.
  • size(): Returns the current size of the Vector.
  • toString(): Returns a String representation of the Vector, containing its elements in order.

These methods provide essential functionalities for manipulating and querying Vector objects in Java, facilitating efficient data management and retrieval operations.

Source Code

import java.util.Iterator;
import java.util.Vector;
public class VectorExample {
    public static void main(String[] args) {
        Vector<String> fruits = new Vector<>();
        fruits.add("Apple");
        fruits.add("Orange");
        fruits.add("Grapes");
        fruits.add("Pine");
        Iterator<String> it = fruits.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

Output

Output

This code demonstrates the basic usage of the Vector class and Iterator interface in Java. It initializes a Vector, adds elements to it, retrieves an Iterator to iterate through the Vector, and prints each element sequentially using the Iterator. This approach shows how to effectively manage and iterate over collections in Java.

The Stack Class

The Stack class in Java extends the Vector class, inheriting its methods for managing dynamic arrays. Additionally, the Stack class introduces specialized methods such as push, pop, peek, and search. These methods enable stack-specific operations: push adds an element to the top of the stack, pop removes and returns the top element, peek returns the top element without removing it, and search determines the position of a specified object within the stack.

The constructor of the Stack class can be represented as,

Stack()

The above constructor is used to create an empty stack. The Stack class uses the First In Last Out (FILO) mechanism.

Methods of Stack class

  • empty(): Returns true if the Stack is empty.
  • peek(): Returns the element at the top of the Stack without removing it.
  • pop(): Removes and returns the element at the top of the Stack.
  • push(): Adds an item to the top of the Stack.

These methods are fundamental for manipulating a Stack data structure in Java, facilitating operations such as checking if the stack is empty, accessing the top element without altering the stack, removing the top element, and adding new elements to the stack's top.

Consider a program that adds String values to a Stack.

Source Code

import java.util.*;
public class StackExample {
    public static void main(String[] args) {
        Stack<String> st = new Stack<>();
        st.push("Java");
        st.push("Programming");
        st.push("Language");
        st.push("Ashish Bhatnagar");
        System.out.println("The element in the Stack: " + st);
        System.out.println("The element at the top: " + st.peek());
        System.out.println("The element popped out of the Stack: " + st.pop());
        System.out.println("The element in the Stack after popping an element: " + st);
        System.out.println("The Result of Searching: " + st.search("a b"));
    }
}

Output

Command Prompt

This code demonstrates basic operations with the Stack class in Java. It initializes a Stack, pushes elements onto it, prints the Stack's contents, performs peek-and-pop operations to retrieve and remove elements from the top of the Stack, and finally, demonstrates searching for an element within the Stack. This example illustrates how to use a Stack data structure for LIFO (Last In, First Out) operations in Java programming.

Summary

The Vector Class and the Stack Class are essential components of the Java Collections Framework, providing robust solutions for managing ordered collections and stack-based data structures, respectively. The Vector Class extends AbstractList and implements List, Cloneable, and Serializable interfaces, offering dynamic array capabilities with built-in synchronization for thread safety. It supports operations like adding, accessing, and modifying elements, making it suitable for scenarios requiring synchronized access and ordered traversal. On the other hand, the Stack Class extends Vector and introduces methods specific to stack operations such as push (adding elements), pop (removing and returning elements), peek (viewing the top element without removal), and search (finding elements). These classes are fundamental in Java programming for efficient data management and implementation of algorithms relying on sequential storage and Last In, First Out (LIFO) behavior.


Similar Articles