gpt4 book ai didi

java - 无法调用 Collections.sort(arrayList)

转载 作者:行者123 更新时间:2023-12-01 07:21:22 25 4
gpt4 key购买 nike

我正在尝试按员工的工资对对象 Employee 的数组列表进行排序。我已将所有 Employee 对象存储在 ArrayList 中,并尝试调用 Collections.sort(list) 但出现错误(eclipse)。请看截图enter image description here

我该怎么办?
我在实现 Comparable<> 接口(interface)时遇到此错误,我已经添加了 方法compareTo enter image description here

最佳答案

您的类 Employee 必须实现 Comparable 才能使用 Collections.sort(),并且您必须定义 Employee 对象应该在 compareTo(Employee e) 方法中进行比较。

所以在你的上下文中,它应该是这样的:

public class Employee implements Comparable<Employee> {

public int compareTo(Employee o) {
//this is an example. Obviously, you can put whatever you want here
return (int)(this.salary-o.salary);
}
}

关于java - 无法调用 Collections.sort(arrayList),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36244635/

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