tags:

views:

2108

answers:

4

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

+7  A: 

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) {
  ...
}
Christian Vest Hansen
It's not really an enum, apparently. But it has a method 'isGreaterOrEqual()'
ripper234
+1  A: 

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.

Rich Seller
+1  A: 

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.

Peter Lawrey
A: 

Another option would be

enum Blah {
 A(false), B(false), C(true);
private final boolean isError;
Blah(boolean isErr) {isError = isErr;}
public boolean isError() { return isError; }

}

From your question, I'm assuming you're using enum to designate some kind of return value, some of which are error states. This implementation has the advantage of not having to add the new return types in a particular place (and then adjust your test value), but has the disadvantage of needing some extra work in initializing the enum.

Pursuing my assumption a bit further, are error codes something for the user? A debugging tool? If it's the latter, I've found the exception handling system to be pretty alright for Java.

Carl