无法使用CustomComparator创建哈希集

时间:2019-02-02 15:02:17

标签: java hashmap hashset

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

enter image description here enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

HashMapHashSet不是排序的集合,因此没有构造函数可以使用Comparator。相反,您必须使用TreeSetTreeMap,其中包含一个重载的构造函数才能使用Comparator。因此,应将此代码更正。

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