compareByIndex<T extends Enum> 静态方法

  1. @Since("2.15")
int compareByIndex<T extends Enum>(
  1. T value1,
  2. T value2
)

通过枚举值的索引比较两个枚举值。

一个通用的 Comparator 函数,用于枚举类型,按照枚举值的索引值对枚举值进行排序,这对应于在 enum 声明中枚举元素声明的源顺序。

示例

enum Season { spring, summer, autumn, winter }

void main() {
  var relationByIndex =
      Enum.compareByIndex(Season.spring, Season.summer); // < 0
  relationByIndex =
      Enum.compareByIndex(Season.summer, Season.spring); // > 0
  relationByIndex =
      Enum.compareByIndex(Season.spring, Season.winter); // < 0
  relationByIndex =
      Enum.compareByIndex(Season.winter, Season.spring); // > 0
}

实现

@Since("2.15")
static int compareByIndex<T extends Enum>(T value1, T value2) =>
    value1.index - value2.index;