Menu

1 / 2

EnumMap and EnumSet: The Java Collections Most Developers Never Use

DEV Community·TheCodeForge·7 months ago
#J2hLzNFP
#real#mistake#creating#enumset#permission
Reading 0:00
15s threshold

Two years ago I was doing a code review and flagged a colleague's

HashMap<OrderStatus, Handler> as "fine, no issues." The tests passed.

The code shipped.

Last year I profiled that same service under load and found the map

lookup on the hot path burning more CPU than it should. The fix was

a one-line change. The only reason I knew about it was because I'd

finally read the java.util.EnumMap source out of curiosity one

afternoon.

This is that story, plus everything I now know about EnumMap and

EnumSet that I wish someone had told me earlier.

The One Fact That Makes Everything Else Click

Every Java enum constant has an ordinal — a zero-based integer

assigned in declaration order:

public enum OrderStatus { PLACED , // ordinal 0 CONFIRMED , // ordinal 1 SHIPPED , // ordinal 2 DELIVERED , // ordinal 3 CANCELLED // ordinal 4 }

Enter fullscreen mode

Exit fullscreen mode

This ordinal is stable for a given JVM session.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.