Java Legacy Collections: Hashtable, Enumeration, Properties, Stack and BitSet
Java 1.0's legacy collections and what to use today: Hashtable vs HashMap, Enumeration and how to convert it, Properties files with defaults and UTF-8, system properties, why Stack lost to ArrayDeque, and BitSet with a sieve of Eratosthenes example.
kvi5hnuCode Sprout team member11 min readOn this page
Before Java 1.2 introduced the collections framework, Java 1.0 shipped a handful of container classes: Vector, Stack, Hashtable, Properties, BitSet and the Enumeration interface. They were later retrofitted to implement the new interfaces, and they are still in the JDK. You'll meet them in older code and in a few APIs that never moved on. This article explains each one, says when it is still the right tool (sometimes it is), and shows what replaces it otherwise.

Hashtable
Hashtable does the same job as HashMap and has essentially the same interface, since it implements Map. The differences:
- Every method is
synchronized, likeVector's methods. That costs time in single-threaded code, and it still doesn't make compound actions or iteration thread-safe. - No
nullkeys or values.put(key, null)throwsNullPointerException, whileHashMapaccepts onenullkey and any number ofnullvalues. - It has legacy methods such as
elements()andkeys(), which returnEnumerations, andcontains(value), a confusingly named alias ofcontainsValue.
For new code, use HashMap for single-threaded use, or ConcurrentHashMap for shared access. ConcurrentHashMap scales far better than a fully locked table, and Part 10 covers it. Keep Hashtable only where an old API requires it.
Enumeration
The legacy classes traverse their elements with the Enumeration interface, whose two methods hasMoreElements() and nextElement() match Iterator's hasNext() and next(). It has no remove.
Some JDK APIs still return enumerations, such as LogManager.getLoggerNames(), ClassLoader.getResources(), NetworkInterface.getNetworkInterfaces() and Vector.elements(). Convert them as soon as you get them:
ArrayList<String> loggerNames = Collections.list(LogManager.getLogManager().getLoggerNames());
LogManager.getLogManager().getLoggerNames().asIterator().forEachRemaining(n -> ...); // Java 9
In the other direction, Collections.enumeration(collection) adapts a collection for an old API that demands an Enumeration. A typical example is SequenceInputStream, which concatenates several streams:
List<InputStream> streams = ...;
var in = new SequenceInputStream(Collections.enumeration(streams));
Property maps
A property map is a map with three special characteristics:
- Keys and values are strings.
- It can be saved to and loaded from a simple text file.
- It can have a secondary table of defaults.
The class is java.util.Properties, and it remains the standard way to read .properties files. Resource bundles, many build tools and lots of frameworks use the format.
var settings = new Properties();
settings.setProperty("width", "600.0");
settings.setProperty("filename", "/home/user/books/notes.txt");
String filename = settings.getProperty("filename");
Saving and loading
try (var out = new FileWriter("program.properties", StandardCharsets.UTF_8)) {
settings.store(out, "Program Properties");
}
try (var in = new FileReader("program.properties", StandardCharsets.UTF_8)) {
settings.load(in);
}
The file is a series of key=value lines. # starts a comment, and store writes your comment followed by a timestamp comment. Since Java 18, store writes the entries sorted by key, which makes the files easier to diff. Setting the system property java.properties.date replaces the timestamp with a fixed value, which is useful for reproducible builds.
Defaults
There are two ways to supply defaults. You can pass one per lookup:
String filename = settings.getProperty("filename", "");
Or you can pack all the defaults into a secondary Properties object and pass it to the constructor:
var defaults = new Properties();
defaults.setProperty("width", "600");
defaults.setProperty("height", "400");
var settings = new Properties(defaults);
A lookup checks the main table first, then the defaults. The defaults can have defaults of their own, but that is rarely useful. Note that keySet() shows only the main table's keys, while stringPropertyNames() includes the defaults.
Property files are flat. People often fake a hierarchy with dotted keys like window.main.color, but Properties doesn't help you work with it. For structured configuration, use the java.util.prefs.Preferences API, or a format like YAML, TOML or JSON with a library.
System properties
System.getProperties() returns a Properties object describing the runtime. You'll usually look up single keys:
String home = System.getProperty("user.home");
String version = System.getProperty("java.version"); // "21.0.1" style since Java 9, "1.8.0_…" before
Always present are java.version, java.vendor, java.home, java.class.path, java.specification.version, java.vm.name, os.name, os.arch, os.version, file.separator, path.separator, line.separator, java.io.tmpdir, user.name, user.home, user.dir, and the encoding properties native.encoding, stdout.encoding and stderr.encoding, among others.
You set your own system properties on the command line with -D:
java -Dapp.threads=8 -Duser.language=fr -Duser.country=CA MyProg
jshell -R-Dapp.threads=8 # pass them to jshell's execution engine
java -XshowSettings:properties -version # list all properties
There are typed helpers for reading them. Integer.getInteger(name) and Long.getLong(name) decode the value, so 0x10 and #10 work as hex, and they return null or your default if the property is missing or malformed. Boolean.getBoolean(name) returns true only if the property equals "true", ignoring case. These names are confusing: Integer.getInteger("8") does not parse the string "8". It looks up a system property named "8". Don't change java.version and other JVM-provided properties.
Stack
Java 1.0 had a Stack class with the familiar push, pop and peek, plus empty() and search(). It extends Vector, which is a design mistake: a stack inherits insertElementAt, remove(int), get(int) and friends, so code can poke at any position. It also synchronizes every call. A further surprise is that iterating over a Stack goes from bottom to top, because it is just a Vector.
Use ArrayDeque through the Deque interface instead. Its push, pop and peek work at the head, it iterates from top to bottom, and it is faster. Article 86 covers deques.
BitSet
BitSet stores a sequence of bits packed into long words. That is 64 bits per word, compared with a byte per element for a boolean[] and far more for a Set<Integer>. It gives you a clean API for single bits without manual masking and shifting:
bits.get(i); // is bit i on?
bits.set(i); // turn it on
bits.clear(i); // turn it off
bits.flip(i); // toggle it
Range versions (set(from, to), clear(from, to), get(from, to)) and whole-set operations (and, or, xor, andNot) work a word at a time, so they are very fast. A BitSet grows automatically when you set a high bit.
A good way to think of a BitSet is as a set of non-negative integers with a modest upper bound. Bit i on means i is in the set:
cardinality()is the number of elements, meaning the bits that are on.length()is the "logical length": one more than the highest set bit.size()is the number of bits of storage currently allocated. It is an implementation detail, not the element count.nextSetBit(i),previousSetBit(i)andnextClearBit(i)let you iterate efficiently, andstream()yields the indexes of set bits as anIntStream.
For sets of enum constants, EnumSet (article 88) uses the same bit-vector idea with a type-safe API.
Example: the sieve of Eratosthenes
The classic BitSet demo finds all primes up to n. Start with every number from 2 to n marked as a candidate. Then, for each i still marked with i² ≤ n, clear every multiple of i starting at i². The bits that remain are exactly the primes:
var sieve = new BitSet(n + 1);
sieve.set(2, n + 1);
for (int i = 2; (long) i * i <= n; i++)
if (sieve.get(i))
for (int k = i * i; k <= n; k += i) sieve.clear(k);
int count = sieve.cardinality(); // 148,933 primes up to 2,000,000
The whole sieve for two million numbers fits in about 250 KB and runs in milliseconds. It isn't a serious benchmark, since it mostly measures bit operations, but it has long been a popular one. On a modern JVM, the JIT-compiled Java version performs about as well as optimized C++.
A complete example
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException {
// 1. Hashtable: a synchronized HashMap that rejects null
Map<String, Integer> table = new Hashtable<>();
table.put("one", 1);
try {
table.put("none", null);
} catch (NullPointerException e) {
System.out.println("Hashtable.put(key, null): NullPointerException");
}
var hashMap = new HashMap<String, Integer>();
hashMap.put(null, 0);
hashMap.put("none", null);
System.out.println("HashMap accepts null key and value: " + hashMap.containsKey(null) + " " + hashMap.containsKey("none"));
// 2. Enumeration and conversions
var vector = new Vector<>(List.of("alpha", "beta", "gamma"));
Enumeration<String> e = vector.elements();
var sb = new StringBuilder();
while (e.hasMoreElements()) sb.append(e.nextElement()).append(' ');
System.out.println("enumeration: " + sb.toString().trim());
ArrayList<String> collected = Collections.list(vector.elements());
System.out.print("Collections.list " + collected + ", asIterator:");
vector.elements().asIterator().forEachRemaining(s -> System.out.print(" " + s.toUpperCase()));
System.out.println();
List<InputStream> streams = List.of(
new ByteArrayInputStream("Hello, ".getBytes(StandardCharsets.UTF_8)),
new ByteArrayInputStream("legacy APIs!".getBytes(StandardCharsets.UTF_8)));
try (var in = new SequenceInputStream(Collections.enumeration(streams))) {
System.out.println("SequenceInputStream: " + new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
// 3. Properties with defaults, store and load
var defaults = new Properties();
defaults.setProperty("width", "600");
defaults.setProperty("height", "400");
defaults.setProperty("theme", "light");
var settings = new Properties(defaults);
settings.setProperty("width", "1024");
settings.setProperty("title", "Grüße 你好");
System.out.println("width " + settings.getProperty("width") + ", height " + settings.getProperty("height")
+ " (from defaults), font " + settings.getProperty("font", "Inter") + " (call default), missing " + settings.getProperty("missing"));
System.out.println("own keys " + new TreeSet<>(settings.keySet()) + ", stringPropertyNames " + new TreeSet<>(settings.stringPropertyNames()));
var writer = new StringWriter();
settings.store(writer, "App Settings");
String[] lines = writer.toString().split("\\R");
System.out.println("store(Writer):");
for (String line : lines)
if (!line.startsWith("#") || line.equals("#App Settings")) System.out.println(" " + line); // skip the timestamp line
var bytes = new ByteArrayOutputStream();
settings.store(bytes, null);
for (String line : bytes.toString(StandardCharsets.ISO_8859_1).split("\\R"))
if (line.startsWith("title")) System.out.println("store(OutputStream) escapes: " + line);
var reloaded = new Properties();
reloaded.load(new StringReader(writer.toString()));
System.out.println("reloaded title " + reloaded.getProperty("title") + ", equals original: " + reloaded.equals(settings));
// 4. System properties
System.setProperty("app.threads", "0x10");
System.setProperty("app.verbose", "TRUE");
System.out.println("Integer.getInteger(app.threads) " + Integer.getInteger("app.threads")
+ ", Boolean.getBoolean(app.verbose) " + Boolean.getBoolean("app.verbose")
+ ", Integer.getInteger(app.missing, 4) " + Integer.getInteger("app.missing", 4));
System.out.println("user.home is set: " + (System.getProperty("user.home") != null)
+ ", running Java 17 or later: " + (Runtime.version().feature() >= 17));
// 5. Stack versus ArrayDeque
var stack = new Stack<String>();
stack.push("bottom");
stack.push("middle");
stack.push("top");
stack.insertElementAt("sneaky", 1); // a stack shouldn't allow this
var deque = new ArrayDeque<String>();
for (String s : List.of("bottom", "middle", "top")) deque.push(s);
System.out.println("Stack peek " + stack.peek() + ", iterates " + stack + "; ArrayDeque peek " + deque.peek() + ", iterates " + deque);
// 6. BitSet: operations and the sieve of Eratosthenes
var a = new BitSet();
a.set(1); a.set(3); a.set(5); a.set(7);
var b = new BitSet();
b.set(3, 7); // bits 3, 4, 5, 6
BitSet and = (BitSet) a.clone(); and.and(b);
BitSet or = (BitSet) a.clone(); or.or(b);
BitSet xor = (BitSet) a.clone(); xor.xor(b);
BitSet andNot = (BitSet) a.clone(); andNot.andNot(b);
System.out.println("a " + a + " b " + b + " and " + and + " or " + or + " xor " + xor + " andNot " + andNot);
System.out.println("a.cardinality " + a.cardinality() + ", a.length " + a.length() + ", a.get(3) " + a.get(3) + ", a.get(4) " + a.get(4));
int n = 2_000_000;
var sieve = new BitSet(n + 1);
sieve.set(2, n + 1); // assume every number from 2 to n is prime
for (int i = 2; (long) i * i <= n; i++)
if (sieve.get(i))
for (int k = i * i; k <= n; k += i) sieve.clear(k); // multiples are not prime
System.out.print("primes up to 2,000,000: " + sieve.cardinality() + "; first ten:");
for (int p = sieve.nextSetBit(0), count = 0; count < 10; p = sieve.nextSetBit(p + 1), count++) System.out.print(" " + p);
System.out.println("; largest " + sieve.previousSetBit(n));
System.out.println("primes below 50 via stream: " + sieve.get(0, 50).stream().boxed().toList());
}
}
Hashtable.put(key, null): NullPointerException
HashMap accepts null key and value: true true
enumeration: alpha beta gamma
Collections.list [alpha, beta, gamma], asIterator: ALPHA BETA GAMMA
SequenceInputStream: Hello, legacy APIs!
width 1024, height 400 (from defaults), font Inter (call default), missing null
own keys [title, width], stringPropertyNames [height, theme, title, width]
store(Writer):
#App Settings
title=Grüße 你好
width=1024
store(OutputStream) escapes: title=Gr\u00FC\u00DFe \u4F60\u597D
reloaded title Grüße 你好, equals original: true
Integer.getInteger(app.threads) 16, Boolean.getBoolean(app.verbose) true, Integer.getInteger(app.missing, 4) 4
user.home is set: true, running Java 17 or later: true
Stack peek top, iterates [bottom, sneaky, middle, top]; ArrayDeque peek top, iterates [top, middle, bottom]
a {1, 3, 5, 7} b {3, 4, 5, 6} and {3, 5} or {1, 3, 4, 5, 6, 7} xor {1, 4, 6, 7} andNot {1, 7}
a.cardinality 4, a.length 8, a.get(3) true, a.get(4) false
primes up to 2,000,000: 148933; first ten: 2 3 5 7 11 13 17 19 23 29; largest 1999993
primes below 50 via stream: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
The Properties section skips the timestamp comment that store writes, so the output stays the same between runs. Note how the stream version escapes even ü, because every character outside ASCII becomes a \u escape. The Stack line shows both design flaws: an element was inserted in the middle, and iteration runs bottom-up.
Common questions
Should I still use Vector, Hashtable or Stack?
Not in new code. Use ArrayList, HashMap and ArrayDeque instead, or ConcurrentHashMap and the other concurrent collections when threads share data. Keep the legacy classes only where an old API requires them.
How do I read a .properties file with non-ASCII characters?
Load it through a Reader with an explicit charset: props.load(Files.newBufferedReader(path, StandardCharsets.UTF_8)). load(InputStream) assumes ISO 8859-1 and expects \uXXXX escapes for other characters.
Why does props.get("key") ignore my defaults?
get is the inherited Hashtable method, and it only looks in the main table. getProperty looks in the main table and then in the defaults. Always use getProperty and setProperty.
How do I check which Java version my program is running on?
Call Runtime.version().feature(), which returns 25 on Java 25. Don't parse the java.version string yourself, because its format changed in Java 9.
When is a BitSet better than a Set<Integer>?
When the integers are non-negative and not too large, such as flags, sieve marks or IDs in a known range. A BitSet uses one bit per possible value and does set operations one 64-bit word at a time. For a few scattered large numbers, a HashSet uses less memory.
API reference
java.util.Enumeration<E> and java.util.Collections
| Method | Description |
|---|---|
boolean hasMoreElements(), E nextElement() | legacy traversal, like hasNext and next |
default Iterator<E> asIterator() (Java 9) | an iterator over the remaining elements |
static <T> Enumeration<T> Collections.enumeration(Collection<T> c) | enumeration over a collection |
static <T> ArrayList<T> Collections.list(Enumeration<T> e) | collects the enumerated elements into an ArrayList |
java.util.Properties
| Method | Description |
|---|---|
Properties(), Properties(Properties defaults) | empty property map, optionally with a defaults table |
String getProperty(String key) | value from the map, else from the defaults, else null |
String getProperty(String key, String defaultValue) | value, or defaultValue if not found |
Object setProperty(String key, String value) | sets a property, returns the previous value |
Set<String> stringPropertyNames() | all keys, including those from the defaults |
void load(Reader in), void load(InputStream in) | reads properties (streams use ISO 8859-1) |
void store(Writer out, String comments), void store(OutputStream out, String comments) | writes properties with a comment and timestamp header |
java.lang.System, Integer, Long, Boolean
| Method | Description |
|---|---|
static Properties System.getProperties() | all system properties |
static String System.getProperty(String key), getProperty(String key, String def) | one system property |
static String System.setProperty(String key, String value) | sets a system property |
static Integer Integer.getInteger(String name), with an int or Integer default | the property decoded with Integer.decode, or the default or null |
static Long Long.getLong(String name), with defaults | the same for long |
static boolean Boolean.getBoolean(String name) | true if the property equals "true", ignoring case |
java.util.Stack<E>
| Method | Description |
|---|---|
E push(E item) | pushes and returns item |
E pop(), E peek() | removes and returns, or returns, the top item; throws EmptyStackException if empty |
java.util.BitSet
| Method | Description |
|---|---|
BitSet(), BitSet(int nbits) | empty bit set, optionally pre-sized |
boolean get(int i), void set(int i), void clear(int i), void flip(int i) | single-bit operations (range overloads exist) |
void and(BitSet s), or, xor, andNot | bitwise operations with another set, in place |
int cardinality() | number of set bits |
int length() | index of the highest set bit plus one |
int size() | bits of storage in use (implementation-specific) |
int nextSetBit(int from), previousSetBit(int from), nextClearBit(int from) | navigate set and clear bits |
IntStream stream() (Java 8) | indexes of the set bits |
Summary
Vector,StackandHashtablesynchronize every method and have cleaner modern replacements:ArrayList,ArrayDequeandHashMaporConcurrentHashMap.- Convert legacy
Enumerations withCollections.listorasIterator(), and adapt collections for old APIs withCollections.enumeration. Propertiesis still the way to handle.propertiesfiles. UsegetProperty/setProperty, a defaults table, and theReader/Writeroverloads with UTF-8.- System properties describe the JVM and environment. Set your own with
-D, read them withSystem.getPropertyor the typed helpers, and useRuntime.version()instead of parsingjava.version. BitSetis a compact, fast set of small non-negative integers, and it is still the right choice for bit-level work.
Practice Questions
Name two behavioural differences between Hashtable and HashMap.
Hashtable synchronizes every method, while HashMap isn't synchronized. Hashtable rejects null keys and values with NullPointerException, while HashMap allows a null key and null values. Hashtable also offers the legacy Enumeration-returning methods keys() and elements().
Why can props.get("width") return null even though props.getProperty("width") returns "600"?
get is the inherited Hashtable method. It looks only in the main table and ignores the defaults table passed to the constructor, while getProperty falls back to the defaults.
What does Integer.getInteger("42") return?
Most likely null. It looks up a system property named "42" and decodes its value. It doesn't parse the string "42". To parse, use Integer.parseInt or Integer.valueOf.
What is the difference between BitSet.length() and BitSet.cardinality()?
length() is one more than the index of the highest set bit, the logical size. cardinality() is the number of set bits, the number of elements in the set. For bits {1, 3, 5, 7}, length() is 8 and cardinality() is 4.
You iterate over a Stack after pushing 1, 2, 3 and get 1 2 3. Why, and what would ArrayDeque give?
Stack extends Vector, so it iterates in index order from the bottom of the stack up. An ArrayDeque used with push iterates from the head, the top of the stack, so you get 3 2 1.
Previous: Java Collections Algorithms: Sorting, Shuffling, Binary Search and Bulk Operations
Next: Java Threads: Creating and Running Threads with Runnable and Thread
Related reading
- Java Collections Algorithms: Sorting, Shuffling, Binary Search and Bulk Operations
- Java Collection Copies and Views: Immutable Collections, Subranges and Unmodifiable Views
- Java Map Views and Special Maps: LinkedHashMap, EnumMap, WeakHashMap and IdentityHashMap
- Java Maps: HashMap, TreeMap and Updating Map Entries
- Java Queues and Deques: ArrayDeque, LinkedList and PriorityQueue

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.