While HashMap
and TreeMap
dominate everyday Java development, there are two highly specialized Map
implementations that offer unique benefits: EnumMap and WeakHashMap.
EnumMap
is optimized for enums—offering blazing speed and minimal memory usage.WeakHashMap
enables automatic removal of entries when keys are no longer referenced—great for caches and memory-sensitive applications.
This tutorial explores both of these lesser-known but powerful tools in the Java Collections arsenal.
Table of Contents
- What are EnumMap and WeakHashMap?
- Java Syntax and Constructors
- Internal Working and Data Model
- Performance and Complexity
- Real-World Use Cases
- Functional Support in Java 8+
- Java Version Enhancements (Java 8–21)
- Comparisons with Other Maps
- Pros and Cons
- Common Mistakes and Anti-Patterns
- Refactoring Legacy Code
- Best Practices
- 📌 What's New in Java [version]?
- Conclusion and Key Takeaways
- FAQ – 10 Expert-Level Questions
What are EnumMap and WeakHashMap?
EnumMap
A specialized Map
for use with enum
keys. Backed by an array and extremely efficient.
enum Day { MON, TUE, WED }
EnumMap<Day, String> schedule = new EnumMap<>(Day.class);
schedule.put(Day.MON, "Gym");
WeakHashMap
A Map
where keys are held using weak references. If a key is no longer referenced elsewhere, the GC can reclaim its entry.
Map<Object, String> map = new WeakHashMap<>();
Object key = new Object();
map.put(key, "value");
key = null;
System.gc(); // Entry may be removed
Java Syntax and Constructors
EnumMap<Status, String> messages = new EnumMap<>(Status.class);
WeakHashMap<Object, String> weakMap = new WeakHashMap<>();
Internal Working and Data Model
EnumMap Internals
- Uses ordinal values of enums as array indices
- No hashing or collision handling needed
- Offers O(1) performance for all operations
WeakHashMap Internals
- Keys stored as
WeakReference
- Uses ReferenceQueue to track cleared keys
- Relies on GC for automatic cleanup
Performance and Complexity
Feature | EnumMap | WeakHashMap |
---|---|---|
Key Type | Enum only | Any Object |
get/put/remove | O(1) | O(1) average |
Thread-safe | No | No |
GC-Aware | No | Yes |
Backing Store | Array | Hash table + WeakReference |
Real-World Use Cases
EnumMap
- State machines
- Enum-based configurations
- Feature toggles or enum-command mappings
WeakHashMap
- Memory-sensitive caches
- Avoiding memory leaks in plugins or listeners
- Metadata storage in frameworks (e.g., annotations)
Functional Support in Java 8+
enum Mode { READ, WRITE }
EnumMap<Mode, String> perms = new EnumMap<>(Mode.class);
perms.put(Mode.READ, "r");
perms.put(Mode.WRITE, "w");
perms.forEach((k, v) -> System.out.println(k + ":" + v));
WeakHashMap<Object, String> weakMap = new WeakHashMap<>();
weakMap.put(new Object(), "temp");
weakMap.forEach((k, v) -> System.out.println(v));
Java Version Enhancements
Java 8
forEach
,computeIfAbsent
,merge
, etc.
Java 9+
- No major updates to these classes
Map.of()
not compatible with EnumMap or WeakHashMap
Java 21
- Internal optimizations in garbage collection improve WeakHashMap behavior
Comparisons with Other Maps
Feature | EnumMap | HashMap | WeakHashMap |
---|---|---|---|
Key Type | Enum only | Any | Any Object |
Null Keys | Not allowed | 1 allowed | 1 allowed |
Ordering | Enum order | Unordered | Unordered |
GC behavior | No effect | No effect | GC cleans keys |
Performance | Very fast | Fast | Moderate |
Pros and Cons
EnumMap
✅ Pros
- Super fast and memory-efficient
- Predictable iteration order (enum order)
❌ Cons
- Only works with enum keys
WeakHashMap
✅ Pros
- Automatic cleanup via GC
- Reduces memory leaks
❌ Cons
- Non-deterministic behavior
- Not for critical logic
Common Mistakes and Anti-Patterns
❌ Using EnumMap with null keys
Throws NullPointerException
. EnumMap does not allow null keys.
❌ Assuming WeakHashMap is a cache
It can be cleared unpredictably. Use LinkedHashMap
with access order or libraries like Caffeine for production caches.
❌ Iterating WeakHashMap after GC
The map might be empty after GC, so don’t rely on its size.
Refactoring Legacy Code
Before:
Map<MyEnum, String> map = new HashMap<>();
After:
EnumMap<MyEnum, String> map = new EnumMap<>(MyEnum.class);
Before:
Map<Object, String> meta = new HashMap<>();
After:
Map<Object, String> meta = new WeakHashMap<>();
Best Practices
- Use
EnumMap
wherever enums are keys—it’s unbeatable in speed and memory - Avoid critical logic with
WeakHashMap
due to GC unpredictability - For safe caching, prefer dedicated caching libraries
📌 What's New in Java [version]?
Java 8
forEach
,merge
,compute
on both EnumMap and WeakHashMap
Java 9
Map.of()
for lightweight immutable maps
Java 10
var
for simpler declarations
Java 21
- GC improvements benefit WeakHashMap cleanup behavior
Conclusion and Key Takeaways
EnumMap
is a must-use when enum keys are involved—fast, lightweight, and predictableWeakHashMap
is ideal for optional metadata and temporary caches, but not for mission-critical systems- Understand their strengths and constraints to use them effectively in modern applications
FAQ – 10 Expert-Level Questions
1. Can EnumMap store null keys?
No. It throws NullPointerException
.
2. What is the iteration order of EnumMap?
The natural order of enum constants.
3. Is WeakHashMap thread-safe?
No. Wrap it with Collections.synchronizedMap()
if needed.
4. What’s the difference between HashMap and WeakHashMap?
WeakHashMap allows GC to remove entries when keys are no longer strongly referenced.
5. Does EnumMap use hashing?
No. It uses ordinal-based indexing.
6. Can I use Map.of()
to create an EnumMap?
No. You'll need to populate it manually.
7. Can WeakHashMap cause memory leaks?
Yes, if you hold strong references to keys elsewhere.
8. Is EnumMap suitable for high-performance systems?
Absolutely, when enum keys are used.
9. How to clean WeakHashMap manually?
You can’t. It depends entirely on GC behavior.
10. Are these maps supported by Java 21 optimizations?
Yes. GC improvements indirectly benefit WeakHashMap. EnumMap remains performant as-is.