Most of the times an enumeration containing all elements is shown in a drop down in the user interface. We have a need to show only 2 out of 5 fields in the user interface. What would be an easier way to fetch this data, by somehow leveraging the same functions available for an enumeration.
enum Color {RED, GREEN, BLACK, BLUE, YELLOW};
We have a requirement to show only {RED, BLUE} in a certain user interface?
We've learned that we can't create a subclass of an existing enum. However, an interface is extensible. Therefore, we can emulate extensible enums by implementing an interface.
As we have learned, we cannot inherit enum classes in Java. However, enum classes can implement interfaces.
The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.
An enumerated set is a finite or countable set or multiset S together with a canonical enumeration of its elements; conceptually, this is very similar to an immutable list.
Sounds like a job for EnumSet
:
EnumSet<Color> set = EnumSet.of(Color.RED, Color.BLUE);
EnumSet.of(Color.RED, Color.BLUE)
see java.util.EnumSet
If enum contains some custom methods (e.g., to display Red
instesd of RED
)
public enum Color {
RED("Red"), GREEN("Green"), BLACK("Black"), BLUE("Blue"), YELLOW("Yellow");
private final String display;
private Color(String display) {
this.display = display;
}
@Override
public String toString() {
return display;
}
public static EnumSet<Color> getSubSetOfValues() {
return EnumSet.of(RED, BLUE); // return Red and Green
//return EnumSet.range(GREEN, BLUE); // return Green, Black and Blue
}
}
Color.values(); // all elements.
Color.getSubSetOfValues(); // subset
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With