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'.
By the way unlike comparing String in Java, you can use both == and equals() method to compare Enum, they will produce same result because equals() method of Java. lang. Enum internally uses == to compare enum in Java.
Enum constants are only comparable to other enum constants of the same enum type. The natural order implemented by this method is the order in which the constants are declared. Parameters: o - the object to be compared.
The compareTo() method of Enum class compares this enum object with the defined object for order. Enum constants can only be compared to other enum constants of the same type. Returns: A negative integer, if this enum is less than the defined object.
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 int
s, then comparison is trivial.
if (ErrorLevel.ERROR.compareTo(someOtherLevel) <= 0) { ... }
A version which is much more expressive would be
myError.isErrorOrAbove(otherError)
or
myError.isWorseThan(otherError)
This way you can define the ordering inside the Enum and can change the implementation internally if you like. Now the clients of the Enum can compare values without knowing any details about it.
A possible implementation whould be
public enum ErrorLevel { INFO(0), WARN(1), ERROR(2), FATAL(3); private Integer severity; ErrorLevel(int severity) { this.severity = severity; } public boolean isWorseThan(ErrorLevel other) { return this.severity > other.severity; } }
I also would not recommend using the ordinal() method for comparison, because when somebody changes the order the Enum values are defined you could get unexpected behaviour.
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