【问题标题】:Using compareTo() method each time with different sorting property每次使用具有不同排序属性的 compareTo() 方法
【发布时间】:2019-09-15 07:33:58
【问题描述】:

我正在使用compareTo() 方法对名为image 的自定义对象的ArrayList 进行排序,但在我的应用程序中,有时我需要根据goodMatches 等特定属性对数组进行排序,以及其他有时我需要根据对象的另一个属性或属性对数组进行排序,但对于不同的排序,我不能多次覆盖 compareTo() 方法。

我已经尝试对 Object 使用 flags 属性,但问题是其他属性是浮点类型,我需要保留方法 compareTo 以将浮点而不是整数作为 goodMatches 返回。任何人都可以帮助我克服这个问题而无需创建另一个对象类,任何帮助将不胜感激,下面是我的compareTo()代码:

@Override
public int compareTo(image compareImg) {
    int compareMatches=((image)compareImg).getGoodMatches();      
    return compareMatches - this.goodMatches;
}

【问题讨论】:

  • 您需要创建自定义比较器
  • 你能澄清一下这个说法吗:“对于不同的种类,我不能多次重写 compareTo() 方法”?我假设您从代码中的不同位置调用sort,那么您不能为每个用例定义不同的Comparators 吗?
  • @Sindbad90 compareTo 在使用“实现 Comparable”时已经实现,例如我的情况:公共类图像实现 Comparable{},所以我不能为其他排序类型编写第二个或第三个 compareTo跨度>

标签: java android sorting arraylist


【解决方案1】:

给定以下Image 类(使用大写的类名)

class Image {
    private int goodMatches;
    private float anotherProperty;

    .....

    public int getGoodMatches() {
        return goodMatches;
    }

    public float getAnotherProperty() {
        return anotherProperty;
    }
}

您可以为每个属性创建一个Comparator

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 上的 sort 方法对你的列表进行排序:

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());

【讨论】:

  • 感谢您的回答,但我将此代码放在对象类或 mainActivity 中的位置,我需要始终按降序排序
  • 您可以将比较器放在自己的文件中,它们是类。并在需要的地方使用排序。我将添加一个 sn-p 用于逆序
  • 非常感谢您,您的代码似乎可以工作,我会尝试并返回给您
  • 抱歉打扰了,但我怎样才能返回 float 而不是 int?如果我使用 float 他们说该类型是兼容的
  • 使用Float.compare 而不是Integer.compare
【解决方案2】:

不要重写compareTo(),而是尝试创建一个名为Comparator 的类,它通过传递ICompare 的实现来创建一个比较器(确定哪个对象具有更高优先级的判断器)。

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 对象。然后用它来比较图像类型的对象。

我想在这里告诉你,你可以在这里使用泛型,但我这样做不仅仅是因为我想让它简单明了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 2014-03-21
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    相关资源
    最近更新 更多