Can I set enum start value in Java?
In Java, enum
does not support a custom start value. Rather, specific values are laid out using a constructor:
You could call Status.START.getCode()
to get 100
. An enum in Java is more about defining constants with names than defining a sequence of numbers.
Enum Custom Values: How-to Guides
Java's enum
types are pretty much classes. Not just integers. Let's drill down into patterns and tools crucial for their power utilization.
Building Enums with Constructors & Fields
Embedding a constructor, private fields, and methods within an enum class gives it the feel of a fully-fledged class:
Invoke Role.ADMIN.getRoleId()
and you'll get 1
; the power of custom values unleashed!
Leveraging Static Maps and Ordinals
A static Map
can be used to map constants to custom values:
This method lets us use a lookup table of custom values for each enum constant.
Switch Case for Conditional Handling
switch
statement is an amazingly powerful tool that enums excel with:
A succinct switch-based logic revolving around enum values.
TreeMap for Ordered Mapping
When order matters, TreeMap
is your go-to tool:
Retrieval is simple as Priority.HIGH.getLevel()
, giving you 3
.
Centralized Method for Value Retrieval
A single static method is a great way to retrieve a value across multiple enum constants:
Operation.getOperationByOrdinal(1)
gets you the SUBTRACT
operation.
Using Ordinals for Custom Values
The ordinal can be a base value for customizable values:
Numerical sequencing now begins at 10
when you call Step.ONE.getCustomValue()
.
Enriched patterns in Java Enums
Adding a Cherry on top of our enumeration cake with more patterns.
Caching Values, Conserving Memory
Avoiding class reinstantiation aids memory conservation and processing, by caching values:
This is perfect for constant values frequented in multiple queries.
Singleton Pattern as a Cinch
Enums are great for singletons for their built in instance control, an elementary and serialization safe pattern:
Singleton.INSTANCE.getResource()
guarantees a single initialization.
Dynamic Behavior with Anonymous Classes
Anonymous classes enable dynamic behavior for each enum constant:
Each enum constant provides a new implementation, granting different success behaviors.
Was this article helpful?