Enums and nested classes series: 1. Enums are classes · 2. Enums in production · 3. Nested classes and lambdas
Inside one JVM, enums are almost impossible to misuse; trouble starts when enum values leave the JVM for a database, JSON or another client. After this post you can pick EnumSet/EnumMap correctly, write an enum singleton, persist enums with JPA without corrupting old data, and add constants to an API without breaking clients. Read part 1 first (enums as classes, values/valueOf/ordinal).
At a glance:
flowchart TD
E[Enum] --> DB{How to store?}
DB -->|ORDINAL| O["Insert constant: data wrong"]
DB -->|STRING| S["Reorder-safe, tied to name"]
DB -->|AttributeConverter| AC["Stable code, more code"]
E --> API[API]
API --> CL["Client: UNKNOWN + @JsonEnumDefaultValue"]
API --> SV["Server: 400 on unknown"]
E --> COL["EnumSet / EnumMap: fast"]
E --> SG["One constant: singleton"]
1. EnumSet and EnumMap
Key idea: when elements or keys are enums, use EnumSet/EnumMap instead of HashSet/HashMap. They’re built on ordinal, so operations are bit math and array access.
enum Permission { READ, WRITE, DELETE, ADMIN }
Set<Permission> editor = EnumSet.of(Permission.READ, Permission.WRITE);
Set<Permission> others = EnumSet.complementOf(EnumSet.copyOf(editor)); // [DELETE, ADMIN]
Set<Permission> upToWrite = EnumSet.range(Permission.READ, Permission.WRITE);
Map<PaymentMethod, Long> totals = new EnumMap<>(PaymentMethod.class);
totals.merge(PaymentMethod.CARD, 100L, Long::sum);
EnumSet |
EnumMap |
|
|---|---|---|
| Under the hood | a bit vector (a row of bits): each constant is one bit at its ordinal |
an array indexed by ordinal |
| Operations | contains/add/remove are bit operations; containsAll/retainAll between two EnumSets are ANDs/ORs on longs |
no hashing, no collisions, no Entry object per element |
- Both iterate in the enum’s declaration order, stable and predictable (unlike
HashMap). - Neither accepts
null(NullPointerException) and neither is thread-safe; wrap withCollections.synchronizedMapor use aConcurrentHashMapif needed. EnumSetfully replaces C-style “bit flags” (int flags = READ | WRITE): same performance, but typed and readable when printed.
2. The enum singleton
Key idea: an enum with exactly one constant is the singleton style Effective Java recommends, because the JVM handles initialization, reflection and serialization for you.
public enum IdGenerator {
INSTANCE;
private final AtomicLong sequence = new AtomicLong();
public long next() { return sequence.incrementAndGet(); }
}
long id = IdGenerator.INSTANCE.next();
Compared with a hand-written singleton (private static final plus a private constructor):
- Thread-safe initialization for free: the JVM initializes a class exactly once, even under concurrent access. No double-checked locking.
- Reflection-proof:
Constructor.newInstanceon an enum throwsIllegalArgumentException: Cannot reflectively create enum objects. With a regular class,setAccessible(true)gets you a second instance. - Serialization-proof: deserializing always returns the existing instance. A regular singleton needs a hand-written
readResolve().
Downsides: no separate lazy initialization (it’s created when the enum first loads, usually fine), it can’t extend another class, and like any static singleton it’s hard to replace in tests. In Spring, a singleton is normally a singleton-scoped bean managed by the container (see IoC and DI); the enum singleton fits dependency-free utilities and code outside the container.
3. Enums at system boundaries: database, APIs, serialization
Key idea: once enum values leave the JVM, constant names and order become a contract with old data and with clients. Changing them has to go through a migration or an API evolution process.
3.1. JPA: ORDINAL, STRING or a stable code
Key idea: don’t use ORDINAL (the @Enumerated default). Use STRING, or an AttributeConverter with dedicated codes when constant names must change freely. The ORM and JPA post already says to use STRING; here’s the full reasoning.
STRING ties Java constant names to the data: renaming E_WALLET to WALLET for prettier code means a migration, and every service reading the same table must change too. To decouple completely, give the enum a stable code and use a converter (AttributeConverter — a JPA class that translates a Java value to a column value and back):
public enum PaymentMethod {
CARD("C"), BANK_TRANSFER("B"), E_WALLET("W");
private final String code;
PaymentMethod(String code) { this.code = code; }
public String code() { return code; }
private static final Map<String, PaymentMethod> BY_CODE =
Arrays.stream(values()).collect(Collectors.toUnmodifiableMap(PaymentMethod::code, m -> m));
public static PaymentMethod fromCode(String code) {
PaymentMethod m = BY_CODE.get(code);
if (m == null) throw new IllegalArgumentException("Unknown payment method code: " + code);
return m;
}
}
@Converter(autoApply = true)
public class PaymentMethodConverter implements AttributeConverter<PaymentMethod, String> {
@Override
public String convertToDatabaseColumn(PaymentMethod m) { return m == null ? null : m.code(); }
@Override
public PaymentMethod convertToEntityAttribute(String code) {
return code == null ? null : PaymentMethod.fromCode(code);
}
}
When you add a constant in Java, the database migration must ship before the deployment that writes it. The database should also guard the set of valid values itself (a CHECK constraint), not rely only on the Java enum.
Hibernate 6 generates CHECK constraints, and the address component schema example
When Hibernate 6 generates the schema, enum columns usually come with a CHECK constraint listing the allowed values (or a native ENUM type on MySQL). Adding a constant in Java without a migration that updates the constraint makes INSERTs fail. In production, manage the schema with Flyway/Liquibase, and that migration must ship before the deployment that uses the new constant.
The address component schema in Architecture docs part 2: ADRs and an address component example is an example of the database guarding its own values: capture_method, verify_status and channel are text columns storing constant names, and the first two have a CHECK (... IN (...)). An unknown value is rejected at insert time, even from an SQL script that never goes through the Java code. Adding an enum value then means a migration that updates the CHECK.
3.2. Enums in APIs and how they evolve
Key idea: renaming or removing a constant in an API is an obvious breaking change; adding one can break clients too. The server only adds and announces it, clients read tolerantly, and incoming requests are validated strictly.
For API design and versioning in general, see REST API design.
3.3. Enum serialization
Key idea: both Java serialization and Jackson write only the constant’s name (name()), so renaming or removing a constant makes old data unreadable. For custom codes in JSON, use @JsonValue + @JsonCreator.
- Java serialization: writes the name and reads back with
Enum.valueOf, so you get the existing instance. Enum fields are not written. Renaming or removing a constant makes old data throwInvalidObjectException. - Jackson: writes
name()by default (nottoString(), unless you enableWRITE_ENUMS_USING_TO_STRING). Custom code:@JsonValueon the method returning the code, and a static factory annotated with@JsonCreatorto read it back. - An enum’s
hashCode()is an identity hash and differs between JVM runs. Don’t use it for partitioning, sharding or anything persisted; usename().hashCode()or a dedicated code for a stable value.
What Java serialization ignores in an enum
- Enum fields are not serialized. If an enum (unwisely) has a mutable field, after deserialization you see the current value in the receiving JVM, not the value at write time.
- A
serialVersionUIDdeclared in an enum is ignored (it’s always0L); customreadObject,writeObjectandreadResolvemethods are ignored too.
Exercises
1. Payment methods with stable codes for the database and reports
Task: a payment-method enum must be stored in the database as a fixed one-character code (so renaming constants in code doesn’t affect the data), fail clearly on an unknown code, and compute totals per method from a list of transactions.
Solution 1: stable codes and totals with EnumMap
The PaymentMethod enum and PaymentMethodConverter from section 3.1. Totals per method use an EnumMap:
record Txn(PaymentMethod method, long amount) {}
static Map<PaymentMethod, Long> totals(List<Txn> txns) {
return txns.stream().collect(Collectors.groupingBy(
Txn::method,
() -> new EnumMap<>(PaymentMethod.class),
Collectors.summingLong(Txn::amount)));
}
// {CARD=150, BANK_TRANSFER=10} (always in declaration order)
toUnmodifiableMap throws IllegalStateException while building BY_CODE if two constants share a code, so a declaration mistake shows up as soon as the enum loads. Add a unit test that iterates values() and asserts fromCode(m.code()) == m to lock in the contract.
2. Permissions with EnumSet, stored as a bitmask
Task: a system has permissions (read, write, delete, export, admin) and roles, each role being a set of permissions. Write a check for whether a user (who may have several roles) has a given permission, and store their effective permission set in a BIGINT column so it can be read back.
Solution 2: EnumSet, fixed bits and the limits of a bitmask
import java.util.*;
public class Perms {
enum Permission {
READ(0), WRITE(1), DELETE(2), EXPORT(3), ADMIN(4);
private final int bit; // fixed bit position, never ordinal()
Permission(int bit) { this.bit = bit; }
private static final Map<Integer, Permission> BY_BIT = new HashMap<>();
static {
for (Permission p : values()) {
if (BY_BIT.put(p.bit, p) != null) throw new IllegalStateException("duplicate bit " + p.bit);
}
}
static long toMask(Set<Permission> perms) {
long mask = 0;
for (Permission p : perms) mask |= 1L << p.bit;
return mask;
}
static EnumSet<Permission> fromMask(long mask) {
EnumSet<Permission> result = EnumSet.noneOf(Permission.class);
for (int bit = 0; bit < Long.SIZE; bit++) {
if ((mask & (1L << bit)) == 0) continue;
Permission p = BY_BIT.get(bit);
if (p == null) throw new IllegalArgumentException("unknown permission bit " + bit);
result.add(p);
}
return result;
}
}
enum Role {
VIEWER(EnumSet.of(Permission.READ)),
EDITOR(EnumSet.of(Permission.READ, Permission.WRITE, Permission.EXPORT)),
ADMIN(EnumSet.allOf(Permission.class));
private final Set<Permission> permissions;
Role(EnumSet<Permission> permissions) { this.permissions = Collections.unmodifiableSet(permissions); }
Set<Permission> permissions() { return permissions; }
}
static boolean can(Set<Role> roles, Permission needed) {
return roles.stream().anyMatch(r -> r.permissions().contains(needed));
}
public static void main(String[] args) {
Set<Role> user = EnumSet.of(Role.VIEWER, Role.EDITOR);
System.out.println(can(user, Permission.EXPORT)); // true
System.out.println(can(user, Permission.DELETE)); // false
EnumSet<Permission> effective = EnumSet.noneOf(Permission.class);
user.forEach(r -> effective.addAll(r.permissions()));
long mask = Permission.toMask(effective);
System.out.println(effective + " -> " + mask); // [READ, WRITE, EXPORT] -> 11
System.out.println(Permission.fromMask(mask)); // [READ, WRITE, EXPORT]
try {
Permission.fromMask(1L << 9);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage()); // unknown permission bit 9
}
}
}
- Each role holds an
EnumSetwrapped inCollections.unmodifiableSet, because enum constants are JVM-wide singletons; a mutable set there would be global mutable state. - The bitmask uses an explicit
bitfield, neverordinal(). That’s exactly theEnumType.ORDINALtrap: inserting a new permission in the middle of the enum would change the meaning of every stored mask. - The
staticblock rejects duplicate bits as soon as the enum loads;fromMaskthrows a clear error on an unknown bit (written by a newer version of the code) instead of silently dropping it.
The senior view: a bitmask is compact but hard to query in SQL (WHERE perms & 8 <> 0 can’t use an index), hard to read while debugging, and capped at 64 permissions with a long. To filter users by permission, use a role_permission join table. In Spring Security, permissions are usually GrantedAuthority strings; the enum is just where those strings come from.
Remember
- Explain why
EnumSet/EnumMapbeatHashSet/HashMap, and their limits (null, thread safety). - Give three reasons an enum singleton beats a hand-written one, and when a Spring bean is the better choice.
- Explain why
ORDINALcorrupts data, and choose betweenSTRINGand a converter with stable codes. - Know why adding a constant to an API response can break clients, and what the server, the client and request validation each do.
- Know what enum serialization writes and ignores, and why you never persist an enum’s
hashCode().
Interview questions
Mid
Why are EnumMap and EnumSet faster than HashMap/HashSet for enum keys?
Because they’re built on ordinal: EnumSet is a bit vector and EnumMap is an array, so there’s no hashing and no collisions.
For enums with up to 64 constants an EnumSet is a single long with one bit per constant, so add, contains, union and intersection are bit operations. EnumMap indexes an array by ordinal and creates no Entry per element. Both iterate in declaration order. In exchange, they don’t accept null and aren’t thread-safe.
You store an EnumSet in the database as a bitmask. What do you watch out for?
Every constant needs an explicit, fixed bit position, never ordinal(), and you accept that bitmasks are hard to query.
With ordinal(), inserting or reordering constants changes the meaning of every stored mask. Reject duplicate bits when the enum loads; when reading an unknown bit, fail or log clearly (newer code may have written it). A long holds only 64 permissions. Bitmasks are hard to query (perms & 8 <> 0 can’t use an index) and hard to read while debugging; to filter by permission, a join table or a string-array column is usually better.
How does Jackson serialize enums? How do you make the JSON use your own codes instead of constant names?
By default Jackson writes name() and reads back by exact name; for custom codes, use @JsonValue to write and @JsonCreator to read.
On an unknown value Jackson throws InvalidFormatException. You can enable WRITE_ENUMS_USING_TO_STRING/READ_ENUMS_USING_TO_STRING to use toString(). For stable custom codes, put @JsonValue on a method returning the code and add a static factory annotated with @JsonCreator. For clients that must tolerate new values, add an UNKNOWN constant with @JsonEnumDefaultValue and enable READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE.
Senior
How do you store an enum in a database, and how do you evolve it once there’s existing data?
Store it as STRING or through a converter with stable codes, never ORDINAL; evolve it migration-first, and rename with expand/contract.
ORDINAL: inserting or removing a constant shifts the numbers, and old data reads back wrong without any error.STRINGsurvives reordering but ties Java constant names to the data; to decouple completely, give the enum a stable code and use anAttributeConverter.- New constant: run the migration (update the CHECK constraint or the database ENUM type) before deploying code that writes it, and make sure the old version still running during a rolling deploy doesn’t crash on the new value.
- Rename: add the new value, migrate the data, then drop the old one. Never remove a constant while data still uses it.
Why is an enum considered the best way to write a singleton? What are the downsides?
Because the JVM guarantees exactly one instance against concurrency, reflection and serialization; the downside is global state that’s hard to replace in tests.
Enum constants are created exactly once during class initialization, so it’s thread-safe without locks. Reflection can’t create extra instances. Deserialization always returns the existing instance because enums are serialized by name only. Downsides: it can’t extend another class, it’s initialized when the enum loads, and it’s global state that’s hard to replace in tests. In Spring, a singleton should usually be a container-managed bean so it can be injected and mocked; the enum singleton suits dependency-free utilities.
You add a new value to an enum returned by a REST API. Is that a breaking change? How do you design for it?
It can be: clients that don’t know the new value may crash while parsing, so the contract must say the enum is extensible and clients must read tolerantly.
- A client on default Jackson settings throws
InvalidFormatException; clients with exhaustive switches or code generated from OpenAPI may break. - The API contract states that the enum is extensible; clients act as tolerant readers (an
UNKNOWNconstant with@JsonEnumDefaultValueplusREAD_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE). - The server only adds, never renames or removes, and can start emitting a new value after major clients have upgraded or behind an API version.
- Incoming requests are still validated strictly, with a 400 for unknown values.
Useful phrases for interviews
- “I never persist the ordinal; I use
EnumType.STRINGor a converter with stable codes, so reordering constants can’t corrupt data.” - “Adding an enum value is not automatically backward compatible; clients should be tolerant readers and map unknown values to
UNKNOWN.” - “For enum keys I use
EnumMapandEnumSet: an array and a bit vector, no hashing at all.” - “An enum singleton is thread-safe on initialization and survives reflection and serialization.”
- “Schema migrations for a new enum value go out before the code that writes it.”
- “Enum serialization only writes the name, so renaming a constant breaks previously stored data.”
- “When I store a permission set as a bitmask, every constant gets a fixed bit, never its ordinal.”
- “On requests I reject unknown values with a 400; on responses I make clients tolerant.”
Notes based on the Hỏi Dân IT Java Core material plus my own research, rewritten in my own words.