Enum Definition and Characteristics
An enumeration (enum) in Java is a special data type that defines a fixed set of named constants. Introduced in JDK 1.5 (Java 5), enums provide a more readable and type-safe alternative to traditional constant declarasions like public static final variables.
Key Features
- Finite Instances: The number of enum constants is predetermined at definition time.
- Type Safety: Enum types prevent mismatches that occur when using integer constants.
- Readability: Constant names are self-documenting and improve code clarity.
- Extensibility: Enums can include fields, methods, and constructors, offering flexibility beyond simple constant lists.
Benefits
- Define Constant Groups: Enums represent a bounded set of named values, such as days of the week.
- Compile-Time Checking: The compiler enforces valid values, reducing runtime errors.
- Enhanced Readability: Descriptive names make intent clear without extra comments.
- Easier Maintenance: Changes to the constant set are localized to the enum definition.
- Methods and Fields: Add behavior or data per constant, increasing functionality.
- Switch Support: Enums integrate seamlessly with
switchstatements for clean branching. - Replaces Traditional Constants: A more robust and safer approach than
public static finalvariables.
Declaring Enums
Use the enum keyword to define an enum. Each enum type implicitly extends java.lang.Enum (an abstract class), and each constant is an instance of an anonymous subclass.
public enum Color {
RED, GREEN, BLUE;
}
Specialized Enum Classes
EnumMap
EnumMap is a Map implementation tailored for enum keys, located in java.util.
Properties
- High Performance: Backed by an array, offering faster access than
HashMap. - Type Safety: Key type must be an enum, preventing type errors.
- Ordered: Maintains the natural order of enum constants.
- Compact Memory: Less overhead than
HashMapdue to array storage.
Constructors
EnumMap(Class<K> keyType): Creates an empty map for the given enum type.EnumMap(EnumMap<K,? extends V> m): Initializes from anotherEnumMap.EnumMap(Map<K,? extends V> m): Initializes from a map that must contain atleast one entry to infer the key type.
Common Methods
put(K key, V value): Inserts a key-value pair.get(Object key): Retrieves the value for a key.containsKey(Object key): Checks key existence.remove(Object key): Removes the mapping for a key.size(): Returns the number of entries.keySet(): Returns a set of keys.
Example
import java.util.EnumMap;
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class EnumMapDemo {
public static void main(String[] args) {
EnumMap<Day, String> tasks = new EnumMap<>(Day.class);
tasks.put(Day.MONDAY, "Work");
tasks.put(Day.TUESDAY, "Gym");
tasks.put(Day.WEDNESDAY, "Shopping");
String activity = tasks.get(Day.MONDAY);
System.out.println("Monday: " + activity);
boolean containsMonday = tasks.containsKey(Day.MONDAY);
System.out.println("Has Monday? " + containsMonday);
tasks.remove(Day.MONDAY);
System.out.println("After removal: " + tasks);
}
}
Notes
- Not thread-safe; synchronize externally for concurrent access.
- Keys cannot be
null; values may benull.
EnumSet
EnumSet is a specialized Set for enum types, using bitwise operations internally for high efficiency.
Characteristics
- Type Restricted: Only enum constants of a single type are allowed.
- Fast: Bit-level operations outperform
HashSetfor enums. - Ordered: Iteration follows enum declaration order.
- Not Thread-Safe: Requires external synchronization for concurrent use.
Factory Methods (Cannot use new)
noneOf(Class<E> elementType): Empty set.allOf(Class<E> elementType): Set containing all constants.of(E e, E... elements): Set with specified constants.copyOf(Collection<E> c): Copy from a collection.copyOf(EnumSet<E> s): Copy from anotherEnumSet.range(E from, E to): Set of constants fromfrom(inclusive) toto(exclusive). Requires contiguous and ordered constants.complementOf(EnumSet<E> s): Set of all constants not ins.
Operations
Supports standard Set methods (add, remove, contains, size, etc.) as well as bulk operations like addAll, retainAll, etc.
Example
import java.util.EnumSet;
import java.util.Iterator;
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public class EnumSetDemo {
public static void main(String[] args) {
EnumSet<Day> weekdays = EnumSet.of(
Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY, Day.THURSDAY, Day.FRIDAY
);
System.out.println("Weekdays:");
for (Day d : weekdays) {
System.out.println(d);
}
weekdays.add(Day.SATURDAY);
if (weekdays.contains(Day.SATURDAY)) {
System.out.println("Saturday added");
}
weekdays.remove(Day.TUESDAY);
EnumSet<Day> allDays = EnumSet.allOf(Day.class);
allDays.removeAll(weekdays);
System.out.println("Remaining: " + allDays);
Iterator<Day> it = weekdays.iterator();
while (it.hasNext()) {
System.out.println("Iterator: " + it.next());
}
}
}
Restrictions
nullelements are forbidden;NullPointerExceptionotherwise.- Enum constant order and number affect internal performance; large enums are rare in practice.
Practical Use Cases
1. Representing Finite Constant Sets
- Colors: Red, Green, Blue for UI systems.
- Directions: East, South, West, North for games.
- Days: Weekdays for scheduling.
- Seasons: Spring, Summer, Autumn, Winter.
2. Replacing Magic Constants
Enums eliminate scattered constants, improving maintainability, especially with switch statements.
3. State or Type Indicators
- Order Status: Pending, Processed, Shipped, Completed.
- Error Codes: Descriptive names for each error type.
4. Parameter Constraints
Using enums as method parameters restricts valid inputs, reducing bugs.
5. Configuration Options
For application settings (e.g., logging level, animation toggle), enums ensure valid values and type safety.
6. Code Clarity and Maintenance
Enums boost readability and make future changes easier by grouping related constants.
7. EnumSet for Collections
EnumSet provides efficient, type-safe operations for groups of enum constants.