【问题标题】:Unable to create Hashset with CustomComparator无法使用 CustomComparator 创建 Hashset
【发布时间】:2019-02-02 15:02:17
【问题描述】:

使用 CustomComparator 创建 Hashset/Hashmap 时出现以下错误。 我相信语法是正确的,但我不确定它为什么会抛出错误。请帮忙。

【问题讨论】:

标签: java hashmap hashset


【解决方案1】:

HashMapHashSet 不是排序集合,因此没有构造函数来获取 Comparator。相反,您必须使用TreeSetTreeMap,其中包含一个重载的构造函数来接收Comparator。所以代码应该这样更正。

Map<Student, String> empMap = new TreeMap<>(new MyCustComparator());
Set<Student> set = new TreeSet<>(new MyCustComparator());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    相关资源
    最近更新 更多