【问题标题】:Sort an ArrayList of custom class [duplicate]对自定义类的ArrayList进行排序[重复]
【发布时间】:2014-11-20 19:53:22
【问题描述】:

我有一个ArrayList 的自定义Java 用户需要排序。用户只是系统中的用户。然而,用户有许多属性。要创建初始列表,这些是必要的调用:

ArrayList<Identity> contractors = (ArrayList<Identity>) resource.searchUsers(null, null, null, null, null, null, null, null, "Contractor", "active");

resource 对象也是一个自定义 Java 类,具有必要的数据库调用以返回 contractors. 的数组列表

我的问题是如何对具有许多不同属性的复杂项目的数组列表进行排序?

【问题讨论】:

  • 与对简单项目的 ArrayList 进行排序的方式相同。您可以通过Collections.sort(myArrayList) 进行排序。关键在于您编写的 Comparator 的 compare(...) 或 Comparable 的 compareTo(...) 方法。你试过什么?它怎么不工作?
  • Collections.sort(List) T extends Comparable
  • 我已尝试创建项目的子列表,但不知道如何比较列表中的两个项目。

标签: java sorting arraylist


【解决方案1】:

有两个步骤:

class CustomComparator implements Comparator<Identity> {
    @Override
    public int compare(Identitya, Identityb) {
        return // compare here all values
    }
}

然后将此比较器与排序功能一起使用:

Collections.sort(peps, new CustomComparator() );

如果您对排序感兴趣,您必须在比较器中编写登录。

此解决方案比通过 DTO 实现 Comparable 更简洁,因为您可以根据需要创建和使用许多比较器。而且你的代码很干净,易于测试。

这里有有用的链接:

http://www.tutorialspoint.com/java/java_using_comparator.htm

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    相关资源
    最近更新 更多