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

发布于 2024-11-26 18:52:09 字数 914 浏览 0 评论 0 原文

我使用我之前声明的比较器在 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);

由于某种原因,排序试图将我的 ArrayList 的元素转换为可比较对象,即使我传递了一个比较器。为什么会发生这种情况?

如果有任何用处,这是我的堆栈跟踪

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)

I am calling Collections.sort() on an ArrayList using a Comparator that I declared earlier.

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);

For some reason, sort is trying to cast the elements of my ArrayList as Comparables, even though I passed a Comparator. Why might this be happening?

If it's of any use, here is my stacktrace

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雪若未夕 2024-12-03 18:52:09

您传递的 Comparator 可能为 null

Javadoc 指出:

@param c 确定列表顺序的比较器。 null 值表示应使用元素的自然排序

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

The Comparator you passed is probably null.

The Javadoc states:

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

So it's going to assume the arguments are Comparable if the Comparator is null. The code in Arrays.sort is consistent with this. I think it really ought to throw a NPE if the Comparator is null, but it's part of the contract of the method and so can't be changed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文