gpt4 book ai didi

java - 使用可比较的排序字符串属性

转载 作者:行者123 更新时间:2023-11-29 07:02:43 25 4
gpt4 key购买 nike

我有一个员工类和一个客户类。我可以通过员工的 id 和年龄使用 compareTo() 进行排序,因为它们是整数类型。但如何按员工姓名或薪水排序?compareTo 不接受除 int 以外的任何数据类型,抛出编译时异常。

public class Employee implements Comparable<Employee> {

private int id;
private String name;
private int age;
private long salary;

public int getId() {
return id;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public long getSalary() {
return salary;
}

public Employee(int id, String name, int age, int salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}

@Override
public int compareTo(Employee emp) {
//let's sort the employee based on id in ascending order
//returns a negative integer, zero, or a positive integer as this employee id
//is less than, equal to, or greater than the specified object.
return (this.age - emp.age);
}

@Override
//this is required to print the user friendly information about the Employee
public String toString() {
return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
this.salary + "]";
}

}

客户端类

import java.util.Arrays;

public class Test {

public static void main(String a[]){

//sorting custom object array
Employee[] empArr = new Employee[4];
empArr[0] = new Employee(10, "Mikey", 25, 10000);
empArr[1] = new Employee(20, "Arun", 29, 20000);
empArr[2] = new Employee(5, "Lisa", 35, 5000);
empArr[3] = new Employee(1, "Pankaj", 32, 50000);

//sorting employees array using Comparable interface implementation
Arrays.sort(empArr);
System.out.println("Default Sorting of Employees list:\n"+Arrays.toString(empArr));

}
}

我刚刚用谷歌搜索似乎我也可以通过实现比较器来实现它

public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {

@Override
public int compare(Employee e1, Employee e2) {
return (int) (e1.getSalary() - e2.getSalary());
}
};

建议使用比较器或

@Override
public int compareTo(Employee emp) {
// compare salaries, using the builtin Long.compare:
return Long.compare (salary, emp.salary);
}

最佳答案

如果想根据名字排序,可以试试

@Override
public int compareTo(Employee emp) {
return this.name.compareTO(emp.name);
}

关于java - 使用可比较的排序字符串属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23509964/

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