如何在同一个类中创建2个可比较的方法? [英] How do I make 2 comparable methods in only one class?
本文介绍了如何在同一个类中创建2个可比较的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类,我已经通过一个属性排序。
现在我需要做另一件事,我需要创建另一种方式来排序我的数据。
我如何做,所以我可以选择两种方法。
我知道的唯一命令是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 。)
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屋!
查看全文