gpt4 book ai didi

java - 什么可能导致 Collections.sort(List, Comparator) 抛出 ClassCastException?

转载 作者:搜寻专家 更新时间:2023-11-01 01:37:58 24 4
gpt4 key购买 nike

我正在使用我之前声明的比较器在 ArrayList 上调用 Collections.sort()。

ArrayList<Employee> list = new ArrayList<Employee>();
Comparator<Employee> comparator = new Comparator<Employee>() {

public int compare(Employee o1, Employee o2) {
return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
}

};

...

Collections.sort(list, comparator);

出于某种原因,sort 试图将我的 ArrayList 的元素转换为 Comparables,即使我传递了一个 Comparator。为什么会发生这种情况?

如果有用的话,这是我的堆栈跟踪

Exception in thread "Thread-3" java.lang.ClassCastException: processing.app.EmployeeManager$PrettyOkayEmpolyee cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at foobar.Main.doSomeSorting(Main.java:140)
...
at java.lang.Thread.run(Unknown Source)

最佳答案

您传递的 Comparator 可能是 null

Javadoc 声明:

@param c the comparator to determine the order of the list. A null value indicates that the elements' natural ordering should be used.

因此,如果 Comparatornull,它将假定参数为 ComparableArrays.sort中的代码与此一致。我认为如果 Comparatornull,它确实应该抛出 NPE,但它是方法契约的一部分,因此无法更改。

关于java - 什么可能导致 Collections.sort(List<T>, Comparator<? super T>) 抛出 ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6867161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com