比较 Java 枚举值

发布于 2024-07-27 20:06:58 字数 61 浏览 3 评论 0原文

有没有办法检查枚举值是否“大于/等于”另一个值?

我想检查错误级别是否为“错误或更高”。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

时间海 2024-08-03 20:06:58

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

您还可以使用 ordinal 方法将它们转换为 int,那么比较就微不足道了。

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

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) {
  ...
}
喜爱皱眉﹌ 2024-08-03 20:06:58

更具表现力的版本是

myError.isErrorOrAbove(otherError)

or

myError.isWorseThan(otherError)

这样您就可以定义枚举内部的顺序,并且如果您愿意,可以在内部更改实现。 现在,枚举的客户端可以在不知道任何细节的情况下比较值。

可能的实现是

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;
    }
}

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

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.

若言繁花未落 2024-08-03 20:06:58

Java enum 已经在 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();
    }
  };        
}

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

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());
    }
  }
}

Java enum has 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 enum constants 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:

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());
    }
  }
}
杯别 2024-08-03 20:06:58

假设您已按严重性顺序定义了它们,则可以比较每个值的序数。 序数是其在枚举声明中的位置,其中初始常量被分配零序数。

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

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.

琴流音 2024-08-03 20:06:58

我想检查错误级别是否为“错误或以上”。

这样的枚举应该有一个与之关联的级别。 因此,要找到等于或大于的值,您应该比较级别。

使用序数依赖于枚举值出现的顺序。 如果您依赖于此,则应该记录它,否则这种依赖关系可能会导致代码脆弱。

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.

无声无音无过去 2024-08-03 20:06:58

另一种选择是

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

根据您的问题,我假设您正在使用枚举来指定某种返回值,其中一些是错误状态。 此实现的优点是不必在特定位置添加新的返回类型(然后调整测试值),但缺点是在初始化枚举时需要一些额外的工作。

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文