What are Legacy Classes? Explain any four legacy classes of Java’s collection framework with a suitable program.

What are Legacy Classes in Java?

Legacy classes are classes that were part of Java before the Collection Framework was introduced in Java 1.2. These classes were later adapted to work with the Collection Framework using adapter classes or by implementing relevant interfaces like List, Map, etc.

They are found in the java.util package and are still used for backward compatibility.


Four Legacy Classes in Java:

Legacy ClassDescription
VectorResizable array, synchronized, similar to ArrayList.
StackSubclass of Vector, follows LIFO (Last-In-First-Out).
HashtableKey-value pair map, synchronized, similar to HashMap.
EnumerationIterator used in legacy classes to loop over elements.

1. Vector Example

import java.util.Vector;

public class VectorExample {
    public static void main(String[] args) {
        Vector<String> v = new Vector<>();
        v.add("Java");
        v.add("Python");
        v.add("C++");
        
        System.out.println("Vector Elements: " + v);
    }
}

Output:

Vector Elements: [Java, Python, C++]

2. Stack Example

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        
        System.out.println("Popped Element: " + stack.pop());
        System.out.println("Top Element: " + stack.peek());
    }
}

Output:

Popped Element: 30  
Top Element: 20

3. Hashtable Example

import java.util.Hashtable;

public class HashtableExample {
    public static void main(String[] args) {
        Hashtable<Integer, String> ht = new Hashtable<>();
        ht.put(1, "Apple");
        ht.put(2, "Banana");
        ht.put(3, "Mango");

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

Output:

Hashtable: {3=Mango, 2=Banana, 1=Apple}

4. Enumeration Example

import java.util.Vector;
import java.util.Enumeration;

public class EnumerationExample {
    public static void main(String[] args) {
        Vector<String> v = new Vector<>();
        v.add("A");
        v.add("B");
        v.add("C");

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

Output:

Enumeration: A B C

Summary

  • Legacy classes are old but still useful, especially in multi-threaded (synchronized) environments.
  • You can still use them, but modern alternatives like ArrayList, HashMap, and enhanced for loop are preferred for new development.

Leave a Reply

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