Java 如何仅在一个班级中制作 2 个可比较的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4432774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make 2 comparable methods in only one class?
提问by Gondim
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.
我有一个类,我已经按一个属性对其进行了排序。现在我需要做另一件事,我需要创建另一种方式来对我的数据进行排序。我怎样才能做到,所以我可以在两种方法之间进行选择。我知道的唯一命令是 Collections.sort,它将从我想要比较其数据的类中选取方法 compareTo。
Is it even possible?
甚至有可能吗?
采纳答案by jjnguy
What you need to do is implement a custom Comparator
. And then use:
您需要做的是实现自定义Comparator
. 然后使用:
Collections.sort(yourList, new CustomComparator<YourClass>());
Specifically, you could write: (This will create an Anonymous class that implements Comparator
.)
具体来说,您可以编写:(这将创建一个实现 的匿名类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
};
}
}
It could be used like so:
它可以像这样使用:
Collections.sort(yourList, YourClass.getAttribute2Comparator());
回答by jzd
You can only have one compareTo()
method in your class.
你的类中只能有一种compareTo()
方法。
If you want to sort the same class more than one way, create Comparator
implementations.
如果您想以多种方式对同一类进行排序,请创建Comparator
实现。
回答by atk
If the two methods require the exact same footprint, you may be inappropriately overloading a single class with multiple uses, which would be resolved by fixing your class hierarchy - like instead of using "shape", subclass it with "oval", "rectangle", etc.
如果这两种方法需要完全相同的足迹,您可能会不恰当地重载具有多种用途的单个类,这可以通过修复您的类层次结构来解决 - 就像使用“形状”代替“形状”,将其子类化为“椭圆形”、“矩形” , 等等。
If subclassing doesn't make sense, you need to create different comparison classes. In Java, you often use a Comparator for comparisons. Create several (or create a configurable comparator): IsbnComparator, AuthorComparator, etc.
如果子类化没有意义,则需要创建不同的比较类。在 Java 中,您经常使用 Comparator 进行比较。创建多个(或创建一个可配置的比较器):IsbnComparator、AuthorComparator 等。
Oh, and the configurable option would be:
哦,可配置的选项是:
BookComparator implements Compartor { enum FIELD { AUTHOR, ISBN, ... }; setSortOrder(int rank, FIELD field){...} }