我正在使用方法compareTo()
对名为image
的自定义对象的ArrayList
进行排序,但是在我的应用程序中,有时我需要根据特定属性(如goodMatches
(对数组进行排序,而其他时候我需要根据对象的另一个属性或属性对数组进行排序, 但我不能多次覆盖不同种类的compareTo()
方法。
我尝试对对象使用flags属性,但问题是其他属性是浮点型的,我需要保持方法compareTo
以返回浮点数而不是整数作为goodMatches
。任何人都可以帮助我克服这个问题而无需创建另一个对象类,任何帮助将不胜感激,以下是我的compareTo()
代码:
@Override
public int compareTo(image compareImg) {
int compareMatches=((image)compareImg).getGoodMatches();
return compareMatches - this.goodMatches;
}
给定以下Image
类(类名使用大写(
class Image {
private int goodMatches;
private float anotherProperty;
.....
public int getGoodMatches() {
return goodMatches;
}
public float getAnotherProperty() {
return anotherProperty;
}
}
您可以为每个属性创建一个比较器:
class GoodMatchesComparator implements Comparator<Image> {
@Override
public int compare(Image i1, Image i2) {
return Integer.compare(i1.getGoodMatches(), i2.getGoodMatches());
}
}
class AnotherPropertyComparator implements Comparator<Image> {
@Override
public int compare(Image i1, Image i2) {
return Float.compare(i1.getAnotherProperty(), i2.getAnotherProperty());
}
}
然后使用列表上的排序方法对列表进行排序:
List<Image> images = new ArrayList<>();
// populate your list
// sort the list based on the goodMatches property
images.sort(new GoodMatchesComparator());
// sort the list based on the anotherProperty property
images.sort(new AnotherPropertyComparator());
如果需要反向顺序,可以这样做:
images.sort(new GoodMatchesComparator().reversed());
而不是覆盖compareTo()
尝试通过传递 ICompare 的实现来创建一个名为 Comparator
的类,该类创建一个比较器(确定哪个对象具有更高优先级的判断器(。
public interface ICompare{
compare(image obj1, image obj2);
}
Comperator 类:
public class Comperator{
ICompare icompare;
Comperator(ICompare icompare){
this.icompare = icompare;
}
public int compare(image img1, image img2){
return icompare.compare(img1,img2);
}
}
总之,通过传递所需的实现接口来创建任意数量的 Comperator 对象。然后使用它来比较图像类型的对象。
我想在这里告诉你,你可以在这里使用泛型,但我这样做不仅仅是因为我想保持简单明了!