Is there a way to check if an enum value is 'greater/equal' to another value?
I want to check if an error level is 'error or above'.
Is there a way to check if an enum value is 'greater/equal' to another value?
I want to check if an error level is 'error or above'.
All Java enums implements Comparable: http://java.sun.com/javase/6/docs/api/java/lang/Enum.html
You can also use the ordinal method to turn them into ints, then comparison is trivial.
if (ErrorLevel.ERROR.compareTo(someOtherLevel) <= 0) {
...
}
Assuming you've defined them in order of severity, you can compare the ordinals of each value. The ordinal is its position in its enum declaration, where the initial constant is assigned an ordinal of zero.
You get the ordinal by calling the ordinal() method of the value.
I want to check if an error level is 'error or above'.
Such an enum should have a level associated with it. So to find equals or greater you should compare the levels.
Using ordinal relies on the order the enum values appear. If you rely on this you should document it otherwise such a dependency can lead to brittle code.