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

查看:69
本文介绍了如何在没有比较器/可比较器的情况下按字段对对象的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?

注意:使用Java7.

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 进行排序:

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

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

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