【问题标题】:The default (natural) sorting order is: Country and then Week默认(自然)排序顺序是:国家然后是周
【发布时间】:2022-01-25 08:47:29
【问题描述】:

实现类:WeeklyDataProper,扩展类WeeklyData

要求:

  • 默认(自然)排序顺序是:国家,然后是周
  • 可以在HashSet 集合中正确使用该类。如果两个对象具有相同的 Country 和 Week 属性,则它们被视为相等。

我该如何回答问题的第一部分?通过compareTo 方法?

现在的结果是:

int week, String country

我需要:

String country, int week

【问题讨论】:

标签: java sorting collections comparator comparable


【解决方案1】:

首先,HashSetdoes NOT maintain any order

它不保证集合的迭代顺序;特别是,它不保证订单会随着时间的推移保持不变


SortedSet 的实现是TreeSet,它可以使用实现Comparable 接口的对象的自然顺序(因此实现compareTo 方法),或者通过构造函数public TreeSet(Comparator<? super E> comparator) 自定义比较器

所以,WeeklyDataProper 类可以按如下方式实现Comparable 接口(此处省略空检查):

public class WeeklyDataProper extends WeeklyData implements Comparable<WeeklyDataProper> {
    // getters getCountry / getWeek implemented in the parent
    // ...

    @Override
    public void int compareTo(WeeklyDataProper that) {
        int result = this.getCountry().compareTo(that.getCountry());
        if (result == 0) {
            result = Integer.compare(this.getWeek(), that.getWeek());
        }
        return result;
    }
}

然而,实现一个单独的子类只是为了对WeeklyData的集合进行排序可能有点多余,因此可以使用自定义比较器来检索排序后的WeeklyData集合:

SortedSet<WeeklyData> sorted = new TreeSet<>(
    Comparator.<WeeklyData>comparing(WeeklyData::getCountry)
        .thenComparingInt(WeeklyData::getWeek)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2021-09-03
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多