Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Java enum values

Tags:

java

enums

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'.

like image 380
ripper234 Avatar asked Jul 19 '09 11:07

ripper234


People also ask

Can you use == to compare enums in Java?

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.

Is enum comparable 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.

Are enum comparable?

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.


2 Answers

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) {   ... } 
like image 79
Chris Vest Avatar answered Oct 13 '22 11:10

Chris Vest


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.

like image 29
Felix Reckers Avatar answered Oct 13 '22 10:10

Felix Reckers