我正在解决一个问题.我必须创建一个自定义Employee对象的树集,其中的数据应该按薪水排序,但Employee Id必须是唯一的.我知道equals()和hashCode()方法不适用于TreeSet,我们需要在compareTo()方法中编写对象是否相等的逻辑.我正在判断两个员工Id是否相等,然后返回0,这意味着不应添加对象.
但是,由于拥有相同员工Id的员工也在增加,输出并没有达到预期.我试图调试这个,但我没有得到正确的答案.
这是密码.
public class Employee implements Comparable<Employee>{
int empId;
String empName;
double salary;
public Employee() {
super();
}
public Employee(int empId, String empName, double salary) {
super();
this.empId = empId;
this.empName = empName;
this.salary = salary;
}
@Override
public int hashCode() {
return empId;
}
@Override
public boolean equals(Object o) {
if(this == o) return true;
if(o == null || this.getClass() != o.getClass()) return false;
Employee e = (Employee) o;
return (this.empId == e.empId);
}
@Override
public String toString() {
return empId + " " + empName + " " + salary;
}
@Override
public int compareTo(Employee e) {
if(empId == e.empId)
return 0;
if(this.salary < e.salary) {
return -1;
}
else {
return 1;
}
}
}
程序设计的主要方法
public static void main(String[] args) {
TreeSet<Employee> eSet = new TreeSet<>();
eSet.add(new Employee(1, "john", 20000));
eSet.add(new Employee(2, "jim", 10000));
eSet.add(new Employee(9, "mike", 50000));
eSet.add(new Employee(3, "jack", 30000));
eSet.add(new Employee(3, "david", 40000));
eSet.add(new Employee(9, "liam", 80000));
eSet.add(new Employee(9, "brad", 89000));
eSet.add(new Employee(3, "jason", 85000));
eSet.add(new Employee(2, "ted", 35000));
for(Employee e: eSet) {
System.out.println(e);
}
}
上述程序的输出结果如下:
2 jim 10000.0
1 john 20000.0
3 jack 30000.0
2 ted 35000.0
9 mike 50000.0
3 jason 85000.0
在这里,您可以看到具有相同员工Id的员工被添加到树集中,这是不应该发生的.如果我使用的是HashSet,问题就解决了,但我必须使用TreeSet来实现它,以获得排序的行为.
有人能告诉我哪里出了问题吗?