Course contentsShow
← Java
Lesson 603 of 2,87014. EnumerationsFree lesson

EnumMap Performance: Array-Based Implementation

Understand how EnumMap uses ordinal-indexed arrays internally for O(1) operations without hashing.

EnumMap Performance: Array-Based Implementation

What You'll Learn

You'll discover why EnumMap achieves blazing-fast O(1) operations by using a simple array indexed by enum ordinal values—no hashing required.

The Array-Based Secret

Under the hood, EnumMap is remarkably simple and efficient. Instead of using hash codes and buckets like HashMap, it stores values in a plain array where each enum constant's ordinal (its position in the enum declaration, starting at 0) serves as the array index.

How It Works

When you declare an enum, Java automatically assigns each constant a unique ordinal:

  • The first constant gets ordinal 0
  • The second gets ordinal 1
  • And so on...

EnumMap creates an internal array with exactly as many slots as there are enum constants. When you put or get a value:

  1. The key's ordinal is retrieved (a trivial field access)
  2. That ordinal directly indexes into the array
  3. The value is stored or retrieved at that position

No hashing. No collision handling. No bucket searching. Just direct array access.

The Performance Advantage

This design gives EnumMap several benefits:

  • O(1) guaranteed: Array access is constant time, always
  • No hash collisions: Each enum ordinal is unique by definition
  • Compact memory: Only the exact number of slots needed
  • Cache-friendly: Sequential memory layout improves CPU cache utilization

Compare this to HashMap, which must compute hash codes, handle collisions, and potentially resize buckets—all adding overhead that EnumMap completely avoids.

The Trade-Off

This only works because enums are closed sets: you know all possible keys at compile time. That constraint is what enables such dramatic simplification.

Key Takeaway: EnumMap achieves O(1) performance without hashing by using each enum's ordinal as a direct array index—making it the fastest and most memory-efficient map choice for enum keys.