Java enum is a data type that allows you to define a set of related constants.
java.lang.Enum
is a base class for all Java enumeration types, but it’s not necessary to use it directly, you could define enum using enum
keyword.
Let’s take a look at Color
Java enum example:
package com.explainjava;
public enum Color {
RED, GREEN, BLUE
}
If you’ll use a Color
as a class field its value must be one of this predefined set.
Enumeration types are singletons, e.g. you cannot create few RED colors.
Note that all constants in enum are in upper case, follow this convention.
Interesting facts about enums:
- One enum cannot extend another enum in Java, but it can implement an interface.
- Enum types can be marked as
static
, but it’s no sense to do it because all enums are effectively static. - Constructor executes before the static block (usually static block executes before constructor)
Important to know that switch statement supports enums.
Example:
public static void show(Color color) {
switch (color) {
case RED:
System.out.println("RED CASE");
break;
case BLUE:
System.out.println("BLUE CASE");
break;
case GREEN:
System.out.println("GREEN CASE");
break;
}
}
Java Enum Methods
Enum has 3 static methods:
valueOf(String name)
valuesOf(Class<T>enumType, String name)
values()
valueOf
returns a enum constant by its name, e.g. Color.valueOf("RED")
returns Color.RED
.
values()
returns an array of all defined constants.
Enum in Java has 2 non-static methods as well (I don’t count methods from an object class):
String name()
int ordinal()
Method name()
returns a string representation of enum object, e.g. Color.RED.name()
returns RED string.
ordinal()
method returns a position of a constant in enum declaration.
For example:
for (Color color : Color.values()) {
System.out.println(color.ordinal());
}
Results in:
0
1
2
So if you’ll change constant position in the enum ordinal method will return another value.
How To Define Fields and Methods in Enum
You can define your own fields and methods in the enumeration type.
Let’s imagine that you have to work with an old library, that defined colors as usual int constants.
But you don’t want to think about what color is number 3, you want to wrap all that stuff into an enum.
We want to create a method that returns enum constant by int value as well.
Example:
package com.explainjava;
public enum Color {
RED(1), GREEN(2), BLUE(3);
private final int value;
Color(int value) {
this.value = value;
}
public static Color valueOf(int value) {
for (Color color : values()) {
if (color.value == value) {
return color;
}
}
return null;
}
}
I marked value
field as final
.
Java doesn’t force you to do that, but in my opinion, it’s a good practice to do that.
Would be strange if someone can change value during the runtime.
Each enum constant can override methods, for example, we can override toString() method for a GREEN
:
package com.explainjava;
public enum Color {
RED(1),
GREEN(2) {
@Override
public String toString() {
return "I'm green";
}
},
BLUE(3);
private final int value;
Color(int value) {
this.value = value;
}
public static Color valueOf(int value) {
for (Color color : values()) {
if (color.value == value) {
return color;
}
}
return null;
}
}
As you see you can extend enum functionality in different ways.
Java EnumSet
EnumSet
is an interesting class to work with enumeration types.
It provides useful methods to create a new set of enum constants.
You can do like this:
Set<Color> allColors = EnumSet.allOf(Color.class);
Set<Color> yellow = EnumSet.of(Color.RED, Color.GREEN);
Set<Color> noColor = EnumSet.noneOf(Color.class);
Instead of:
Set<Color> allColors = new HashSet<>(Arrays.asList(Color.values()));
Set<Color> yellow = new HashSet<>();
yellow.add(Color.RED);
yellow.add(Color.GREEN);
Set<Color> noColor = new HashSet<>();
EnumSet
represents internally a bit vector data structure, it’s not thread-safe and mutable.
You can make it thread-safe using Collections.synchronizedSet()
method.
How to make it immutable is written in my article.
It doesn’t support null values as well.
EnumSet
iterator traverses the elements in the order in which the enum constants are declared (natural order).
The returned iterator is weakly consistent and it will never throw ConcurrentModificationException
.
Conclusion
Now you know what is enum in Java and how to use it.
Don’t forget that you should define enums for a set of related constants of fixed size.
If you have questions ask me in comments.