如何仅在一个班级中制作 2 个可比较的方法? [英] How do I make 2 comparable methods in only one class?
问题描述
我有一个类,我已经按一个属性对其进行了排序.现在我需要做另一件事,我需要创建另一种方式来对我的数据进行排序.我怎样才能做到,所以我可以在两种方法之间进行选择.我知道的唯一命令是 Collections.sort,它将从我想要比较其数据的类中选取方法 compareTo.
I've got one class, that I sort it already by one attribute. Now I need to make another thing, that I need to create another way to sort my data. How can I make it, so I can choose between the two methods. The only command I know is Collections.sort that will pick up the method compareTo from the class I want to compare its data.
有可能吗?
推荐答案
你需要做的是实现一个自定义的Comparator
.然后使用:
What you need to do is implement a custom Comparator
. And then use:
Collections.sort(yourList, new CustomComparator<YourClass>());
具体来说,您可以编写:(这将创建一个实现 Comparator
的匿名类.)
Specifically, you could write: (This will create an Anonymous class that implements Comparator
.)
Collections.sort(yourList, new Comparator<YourClass>(){
public int compare(YourClass one, YourClass two) {
// compare using whichever properties of ListType you need
}
});
如果您愿意,您可以将这些构建到您的类中:
You could build these into your class if you like:
class YourClass {
static Comparator<YourClass> getAttribute1Comparator() {
return new Comparator<YourClass>() {
// compare using attribute 1
};
}
static Comparator<YourClass> getAttribute2Comparator() {
return new Comparator<YourClass>() {
// compare using attribute 2
};
}
}
可以这样使用:
Collections.sort(yourList, YourClass.getAttribute2Comparator());
这篇关于如何仅在一个班级中制作 2 个可比较的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!