What are legacy classes? Explain any four legacy classes of java’s collection framework with suitable programs

What are legacy classes? Explain any four legacy classes of java’s collection framework with suitable programs.

Answer:-

Legacy Classes in Java Collection Framework

Legacy classes are the original classes provided in earlier versions of Java (before Java 2), which were later integrated into the Java Collection Framework in Java 2 (JDK 1.2). These classes are synchronized, reside in java.util package, and are considered obsolete in many cases but still used for backward compatibility.


Four Legacy Classes

  1. Vector
  2. Stack
  3. Hashtable
  4. Enumeration (interface, often used with legacy classes)

1. Vector

  • Grows dynamically like an ArrayList.
  • Synchronized (thread-safe).
import java.util.*;

public class VectorDemo {
    public static void main(String[] args) {
        Vector<String> v = new Vector<>();
        v.add("Apple");
        v.add("Banana");
        v.add("Cherry");

        System.out.println("Vector Elements: " + v);
    }
}

2. Stack

  • Subclass of Vector.
  • Follows LIFO (Last-In-First-Out).
import java.util.*;

public class StackDemo {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.println("Stack: " + stack);
        System.out.println("Top Element: " + stack.peek());
        System.out.println("Popped: " + stack.pop());
        System.out.println("Stack after pop: " + stack);
    }
}

3. Hashtable

  • Stores key-value pairs.
  • Does not allow null key or null value.
  • Synchronized.
import java.util.*;

public class HashtableDemo {
    public static void main(String[] args) {
        Hashtable<Integer, String> ht = new Hashtable<>();
        ht.put(1, "Java");
        ht.put(2, "Python");
        ht.put(3, "C++");

        System.out.println("Hashtable Elements: " + ht);
    }
}

4. Enumeration

  • Used to iterate through legacy collections (like Vector, Hashtable).
  • Similar to Iterator but older.
import java.util.*;

public class EnumerationDemo {
    public static void main(String[] args) {
        Vector<String> v = new Vector<>();
        v.add("One");
        v.add("Two");
        v.add("Three");

        Enumeration<String> e = v.elements();
        System.out.print("Vector Elements: ");
        while (e.hasMoreElements()) {
            System.out.print(e.nextElement() + " ");
        }
    }
}

Summary Table

Class/InterfaceDescriptionThread Safe
VectorGrowable array, allows duplicatesYes
StackLIFO structure, subclass of VectorYes
HashtableKey-value pairs, no nulls allowedYes
EnumerationRead-only cursor for legacy classesYes

Leave a Reply

Your email address will not be published. Required fields are marked *