英文:
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
Enum
的compareTo()
实现是基于枚举的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<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()));
This will produce the sort
[D, C, B, A]
To change the order to ascending:
return -(second.name().compareTo(first.name()));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论