比较 Java 枚举值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1149671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:15:32  来源:igfitidea点击:

Compare Java enum values

javaenums

提问by ripper234

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 Chris Vest

All Java enums implements Comparable: http://java.sun.com/javase/6/docs/api/java/lang/Enum.html

所有 Java 枚举都实现了 Comparable:http: //java.sun.com/javase/6/docs/api/java/lang/Enum.html

You can also use the ordinalmethod to turn them into ints, then comparison is trivial.

也可以用ordinal方法把它们变成ints,这样比较就不重要了。

if (ErrorLevel.ERROR.compareTo(someOtherLevel) <= 0) {
  ...
}

回答by Rich Seller

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.

您可以通过调用值的 ordinal() 方法来获取序数。

回答by Peter Lawrey

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.

使用 ordinal 依赖于枚举值出现的顺序。如果你依赖它,你应该记录它,否则这种依赖会导致脆弱的代码。

回答by Carl

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.

根据您的问题,我假设您使用 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.

进一步追求我的假设,错误代码对用户有用吗?调试工具?如果是后者,我发现异常处理系统非常适合 Java。

回答by Felix Reckers

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.

通过这种方式,您可以在 Enum 中定义排序,并且可以根据需要在内部更改实现。现在 Enum 的客户端可以在不知道任何细节的情况下比较值。

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.

我也不建议使用 ordinal() 方法进行比较,因为当有人更改 Enum 值的定义顺序时,您可能会出现意外行为。

回答by MaxZoom

Java enumhas already build in compareTo(..)method, which uses the enum position (aka ordinal) to compare one object to other. The position is determined based on the order in which the enumconstants are declared , where the first constant is assigned an ordinal of zero.
If that arrangement is unsuitable, you may need to define you own comparator by adding internal field(s) as shown below:

Java枚举已经内置了compareTo(..)方法,该方法使用枚举位置(又名序数)将一个对象与另一个对象进行比较。位置是根据枚举常量的声明顺序确定的,其中第一个常量被分配零序数。
如果这种安排不合适,您可能需要通过添加内部字段来定义您自己的比较器,如下所示:

import java.util.Comparator;

public enum Day {
  MONDAY(1, 3),
  TUESDAY(2, 6),
  WEDNESDAY(3, 5),
  THURSDAY(4, 4),
  FRIDAY(5, 2),
  SATURDAY(6, 1),
  SUNDAY(0, 0);

  private final int calendarPosition;
  private final int workLevel;

  Day(int position, int level) {
    calendarPosition = position;
    workLevel = level;
  }

  int getCalendarPosition(){ return calendarPosition; }  
  int getWorkLevel() { return workLevel;  }

  public static Comparator<Day> calendarPositionComparator = new Comparator<Day>() {
    public int compare(Day d1, Day d2) {
      return d1.getCalendarPosition() - d2.getCalendarPosition();
    }
  };

  public static Comparator<Day> workLevelComparator = new Comparator<Day>() {
    public int compare(Day d1, Day d2) {
      // descending order, harder first
      return d2.getWorkLevel() - d1.getWorkLevel();
    }
  };        
}

Driver to check if all works:

驱动程序检查是否一切正常:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class EnumTest
{
  public static void main (String[] args) {
     List<Day> allDays = Arrays.asList(Day.values());
     System.out.println("===\nListing days in order of calendar position:");
     Collections.sort(allDays, Day.calendarPositionComparator);
     showItems(allDays);
     System.out.println("===\nListing days in order of work level:");
     Collections.sort(allDays, Day.workLevelComparator);
     showItems(allDays);
  }

  public static void showItems(List<Day> days) {
    for (Day day : days) {
      System.out.println(day.name());
    }
  }
}