如何在没有 Comparator/Comparable 的情况下按字段对对象的 ArrayList 进行排序 [英] How to Sort ArrayList of Objects by a field without Comparator / Comparable

查看:38
本文介绍了如何在没有 Comparator/Comparable 的情况下按字段对对象的 ArrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无法实现 Comparator/Comparable 接口的对象数组列表.

I have an arraylist of objects which cannot implement the Comparator / Comparable interface.

对象有一个字段:'SequenceNumber',它是一个整数.我需要按此字段的顺序(从低到高)对 arraylist 进行排序,而无需实现上述接口.

The objects have a field : 'SequenceNumber' which is an integer. I need to sort the arraylist in order of this field (lowest to highest) without implementing the mentioned interfaces.

是否有一种简单的方法可以做到这一点,我可以手动编写一个排序算法,但想知道是否有一种更有效(并且更无错误)的方法来执行此操作,而我在搜索时错过了这种方法?

Is there an easy way to do this, I can manually write a sorting algorithm but wondering if there is a more efficient (and more bug-free) way of doing this which I have missed while searching?

注意:使用 Java 7.

Note : Using Java 7.

推荐答案

创建一个比较器类来处理排序:

Create a comparator class to handle sorting:

private class MyObjectComparator<MyObject> implements Comparator<MyObject> {

  /**
   * {@inheritDoc}
   */
  @Override
  public int compare(MyObject o1, MyObject o2) {
     return o2.getSequenceNumber() - o1.getSequenceNumber();
  }

}

然后用它对你的 ArrayList 进行排序:

Then sort your ArrayList with it:

Collections.sort(myArrayList, new MyObjectComparator());

这篇关于如何在没有 Comparator/Comparable 的情况下按字段对对象的 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆