覆盖 Enums 中的 compareTo 方法

huangapple go评论85阅读模式
英文:

Overriding compareTo at Enums

问题

我想要将这个枚举按逆字母顺序进行排序并返回。当我尝试使用重写的compareTo方法时,我发现它被声明为final

是否有一种类似于compareTo的方法可以重写枚举的排序方法?

如何才能使得排序结果为:

> D,C,B,A

public enum Test {
    D(4),
    C(1),
    B(2),
    A(3);
}
英文:

I want to sort this Enum as reversed alphabetical order and return it. When I try to use compareTo method by overriding it I saw that it is declared as final.

Is there a way to override Enum similar with compareTo

How is it possible to sort this so I get:

> D,C,B,A

public enum Test { 
 C(1)
 B(2)
 A(3)
 D(4)
}

答案1

得分: 1

EnumcompareTo()实现是基于枚举的ordinal值。

ordinal是:

  • 一个原始的final int
  • 在构造过程中分配
  • 基于枚举声明的顺序
  • 0(零)开始

所以,如果你希望枚举按不同的顺序排序,你只需要按照那个顺序声明它们:

public enum Test { D(4), C(1), B(2), A(3) }

(不确定你传递给构造函数的值代表什么,所以我保持了你的值)

英文:

The Enum implementation of compareTo() is based on the enum's ordinal value.

The ordinal is:

  • A primitive final int value
  • Assigned during construction
  • Based on the order of enum declaration
  • Starting at 0 (zero)

So, if you would like the enum to sort in a different order, you can simply declare them in that order:

public enum Test { D(4), C(1), B(2), A(3) }

(not sure what the values you pass to the constructor represent, so I maintained your values)

答案2

得分: 0

由于您无法在枚举(enum)上实现java.lang.Comparable接口,一种方法是创建一个包装器 java.util.Set 来比较枚举(enum)的名称。

Set<Test> testEnumSet = new TreeSet<>(new Comparator<Test>() {
   @Override
   public int compare(Test first, Test second) {
      return second.name().compareTo(first.name());
   }
});

testEnumSet.addAll(Arrays.asList(Test.values()));

这将产生排序结果

[D, C, B, A]

要更改顺序为升序:

return -(second.name().compareTo(first.name()));
英文:

Since you can't implement the java.lang.Comparable on enum, one way is to create a wrapper java.util.Set to compare the enum on the name.

Set&lt;Test&gt; testEnumSet = new TreeSet&lt;&gt;(new Comparator&lt;Test&gt;() {
   @Override
   public int compare(Test first, Test second) {
      return second.name().compareTo(first.name());
   }
});

testEnumSet.addAll(Arrays.asList(Test.values()));

This will produce the sort

[D, C, B, A]

To change the order to ascending:

return -(second.name().compareTo(first.name()));

huangapple
  • 本文由 发表于 2020年4月6日 08:31:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/61051280.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定