Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 201 ยท Collections

Legacy Collections: Vector, Stack, Hashtable and Enumeration

Learn what Java's legacy collections Vector, Stack, Hashtable and Enumeration do, why they are outdated, and which modern classes replace them in new code.

Before Java had a Collections Framework, it had a handful of container classes that shipped with Java 1.0 in 1996: Vector, Stack, Hashtable, Dictionary and the Enumeration interface. When the framework you've been learning (The Collections Framework) arrived in Java 1.2, these classes were retrofitted to implement List and Map, so old programs kept working. They were never removed, and they never will be, because a lot of code still depends on them.

That's why you need to recognize them. You'll meet them in older codebases, in some JDK APIs that predate the framework, in interview questions, and in answers on the internet written long ago. This lesson shows what each class does, the design problems that made them legacy, and the modern class to use instead.

Why they are called "legacy"

None of these classes is deprecated, and they work correctly. They are legacy because better designs replaced them:

  • Every method is synchronized. Locking was baked into each call, even in single-threaded code where it's pure overhead. Worse, per-method locking does not make sequences of calls safe, so the classes give a false sense of thread safety.
  • Odd inheritance. Stack extends Vector, so a stack lets you insert, read and remove elements anywhere, not just at the top.
  • Inconsistent rules. Hashtable rejects null keys and values; Enumeration has no way to remove an element; method names like addElement and elementAt duplicate the List methods.
  • Better replacements exist for every one of them: ArrayList, ArrayDeque, HashMap, ConcurrentHashMap and Iterator.

Vector: the original growable array

Vector is a resizable array, the ancestor of ArrayList. Since Java 1.2 it implements List, so it has add, get, set and remove. It also keeps its original methods (addElement, elementAt, firstElement, removeElement) and exposes its capacity, the length of its internal array.

Java Vector behaves like a synchronized ArrayList

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The capacity jumps from 10 to 20 when the eleventh element arrives: a Vector doubles its array when full, while ArrayList grows by about 50%. That's a small difference. The real difference is that every Vector method takes a lock on the vector. In single-threaded code you pay for locks you don't need; in multi-threaded code those locks protect each individual call but nothing more.

Synchronized is not the same as thread-safe

Consider "add the item if it isn't there yet". With a Vector, contains and add are each atomic, but another thread can run between them, so two threads can both see "not there" and both add:

Java
// Two threads running this at the same time can BOTH add "job-42"
if (!queue.contains("job-42")) {    // lock taken and released
    queue.add("job-42");            // lock taken again: too late
}

The fix is to hold one lock across the whole sequence, or better, to use a structure that offers the compound operation atomically, such as ConcurrentHashMap.newKeySet().add(...), which returns false if the element was already present. The Synchronization lesson explains race conditions in detail.

The same trap applies to iteration. Locking each call doesn't stop the vector from changing while you loop over it, and the iterator detects this just like an ArrayList iterator does:

Java A Vector's iterator still fails fast

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The loop removes 45, then the next call to the iterator's next() notices that the vector changed and throws. Synchronization was never designed to prevent this. Use removeIf or an explicit Iterator.remove(), as shown in Iterators and ListIterator.

Replacement: ArrayList for normal code. If several threads really share a list, use Collections.synchronizedList(new ArrayList<>()) (and lock it yourself while iterating) or CopyOnWriteArrayList for lists that are read far more often than written; see Concurrent Collections.

Stack: a stack that isn't only a stack

Stack adds the classic stack operations to Vector: push, pop, peek, empty and search. Because it extends Vector, it also inherits every list method, which breaks the idea of a stack. Nothing stops code from calling add(0, x) or remove(3) on it.

Java Stack versus ArrayDeque

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the iteration order. A Stack prints and iterates bottom to top, because it's really a vector with the top at the end. An ArrayDeque used through push/pop iterates top to bottom, which is what most people expect from a stack. If you port code from Stack to ArrayDeque, check any place that loops over the stack or prints it.

Other differences when migrating:

Stack Deque (ArrayDeque) Note
push(x) push(x) ArrayDeque rejects null elements
pop() pop() / poll() pop() throws NoSuchElementException; poll() returns null
peek() peek() Stack.peek() throws on empty; Deque.peek() returns null
empty() isEmpty()
search(x) no direct equivalent rarely needed

Replacement: Deque<T> stack = new ArrayDeque<>();. It's unsynchronized, faster, and its interface only exposes operations that make sense at the ends. The Queues, Deques and PriorityQueue lesson covers it fully.

Hashtable: the original hash map

Hashtable maps keys to values using hashing, just like HashMap, and since Java 1.2 it implements Map. It's the ancestor of HashMap, with three differences that matter:

  1. All methods are synchronized (with the same limits as Vector).
  2. No null keys or values. put(null, ...) and put(..., null) throw NullPointerException. HashMap allows one null key and any number of null values.
  3. It extends the abstract class Dictionary, another 1.0 type that nothing new should use.
Java Hashtable, HashMap and ConcurrentHashMap with null

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The ban on null isn't just a quirk. In a map shared between threads, get(key) returning null would be ambiguous: is the key missing, or is it mapped to null? You can't check with containsKey first, because another thread may change the map between the two calls. ConcurrentHashMap keeps the same rule for the same reason.

Replacements:

  • HashMap for maps used by one thread (most maps). See HashMap.
  • ConcurrentHashMap for maps shared between threads. Its locking is fine-grained (reads don't lock at all), and it offers atomic compound operations like merge, compute and putIfAbsent. That makes it far more scalable than Hashtable, where every call, reads included, waits for one lock.
  • LinkedHashMap or TreeMap when you need a predictable order; Hashtable's order is undefined.

Properties: the descendant you'll still use

java.util.Properties, the class that reads .properties configuration files, extends Hashtable<Object, Object>. It's still the standard way to load simple key-value configuration, so you'll use it even in new code. Stick to its own methods, getProperty and setProperty, which work with strings, rather than the inherited put and get, which accept any object. Properties Files and Configuration covers it.

Enumeration: the original iterator

Enumeration<E> is the 1.0 way to walk through elements. It has two methods, hasMoreElements() and nextElement(), which correspond to Iterator's hasNext() and next(). It has no remove(), and its long names made Iterator a welcome improvement in Java 1.2.

You still get Enumeration objects from a few APIs: Vector.elements(), Hashtable.keys(), Properties.propertyNames(), ClassLoader.getResources(...), NetworkInterface.getNetworkInterfaces() and the old StringTokenizer (which implements Enumeration<Object>). The JDK gives you two easy bridges into the modern world:

Java Converting an Enumeration to modern types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

asIterator() wraps the enumeration without copying, so it's the cheapest bridge; Collections.list(...) copies everything into an ArrayList, which you can then sort, stream or loop over as many times as you like. Collections.enumeration(...) goes the other way when a legacy method requires an Enumeration argument.

One subtle difference: the Enumeration returned by Vector.elements() is not fail-fast. If the vector changes while you enumerate, you get no ConcurrentModificationException, just possibly confusing results. That's one more reason to prefer iterators.

Spotting and migrating legacy code

When you work on older code, the migration is usually mechanical. Declare variables with interface types (List, Map, Deque) as recommended in The Collections Framework, so the change touches only the line with new:

Legacy Single-threaded replacement Shared between threads
Vector ArrayList CopyOnWriteArrayList, Collections.synchronizedList
Stack ArrayDeque (as Deque) ConcurrentLinkedDeque, LinkedBlockingDeque
Hashtable HashMap ConcurrentHashMap
Dictionary Map (interface) Map (interface)
Enumeration Iterator, for-each, streams same

Before you swap a class, check three things:

  • Was the old code relying on synchronization? If threads share the object, pick a concurrent replacement from the right column, and review any check-then-act sequences.
  • Does anything store null? HashMap accepts it where Hashtable threw, so a hidden bug may surface differently. ArrayDeque and ConcurrentHashMap reject null outright.
  • Does anything depend on iteration order? Especially when replacing Stack, whose order is the reverse of ArrayDeque's.

Changing a public method's signature from Vector to List is a breaking API change for callers. In libraries, it's common to keep the legacy type in the public signature and modernize only the internals.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? Stack<Integer> s = new Stack<>(); s.push(1); s.push(2); s.push(3); IO.println(s);

    Stack is a Vector with the top at the end, so it prints and iterates from bottom to top. An ArrayDeque used with push would print [3, 2, 1].
  2. 2. Two threads run if (!v.contains(x)) v.add(x); on the same Vector. What can happen?

    Each call is atomic, but the sequence is not. Another thread can run between contains and add, so both threads can see that x is missing.
  3. 3. What happens on new Hashtable<String, String>().put("key", null)?

    Hashtable rejects both null keys and null values at runtime. HashMap would accept the null value.
  4. 4. Which replacement fits a Hashtable that several threads read and update?

    ConcurrentHashMap is built for sharing between threads, with lock-free reads and atomic operations such as merge and compute. HashMap and TreeMap are not thread-safe.
  5. 5. You receive an Enumeration<String> from an old API and want to sort the values. What's the simplest approach?

    Collections.list copies the remaining elements into a new ArrayList, which you can sort. asIterator() also works if you only need to loop once.

Summary

  • Vector, Stack, Hashtable, Dictionary and Enumeration come from Java 1.0 and were retrofitted into the Collections Framework in Java 1.2. They're not deprecated, but new code shouldn't use them.
  • Their per-method synchronized costs speed and still doesn't make compound actions or iteration safe.
  • Stack extends Vector, so it exposes list operations and iterates bottom to top; use Deque<T> stack = new ArrayDeque<>() instead.
  • Hashtable rejects null keys and values; use HashMap in single-threaded code and ConcurrentHashMap for shared maps.
  • Enumeration is the old iterator; bridge it with asIterator() or Collections.list(...), and go back with Collections.enumeration(...).
  • Properties extends Hashtable and is still in everyday use; use its getProperty/setProperty methods.

Next: Choosing the Right Collection, a decision guide with the performance of every common collection operation.