gpt4 book ai didi

java - 有什么方法可以为列表中的对象字段编写通用排序代码吗?

转载 作者:行者123 更新时间:2023-12-02 05:25:48 25 4
gpt4 key购买 nike

在一次采访中我遇到了这个问题。

编写一个类,它接受 bean 类的字段,并根据传递的字段对包含 bean 对象的列表进行排序。

1) 应该使用什么技术进行排序?我回答了比较器。

2) 我不希望为每个字段创建许多比较器类。你能写一个适用于所有领域的通用比较器吗?下面是我的代码。

请告诉我这是否是正确的做法,或者是否有更好的方法。如果我说错了,请您指正。

公共(public)类 GenericComparatorDemo {

static List<Employee> al = new ArrayList<Employee>();

static{
al.add(new Employee(45, "Vijay", "Bangalore", "Banking", 88, 99999));
al.add(new Employee(13, "Manoz", "Chennai", "Insurance", 48, 28000));
al.add(new Employee(79, "Ajay", "Hyderabad", "Real Estate", 54, 24000));
al.add(new Employee(21, "Sindu", "Noida", "Analyst", 89, 99998));
al.add(new Employee(67, "Honey", "Mumbai", "Social", 88, 111111));
al.add(new Employee(12, "Lucky", "Mysore", "Social", 86, 99997));
}

/**
* @param args
*/
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Please enter the field on which you want to sort employee's...");
final String input = scn.nextLine();
if(null != input && !"".equals(input)){
Collections.sort(al, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
if("id".equals(input)){
return (o1.getId() < o2.getId()) ? -1 : ((o1.getId() == o2.getId()) ? 0 : 1);
}else if("name".equals(input)){
return o1.getName().compareTo(o2.getName());
}else if("location".equals(input)){
return o1.getLocation().compareTo(o2.getLocation());
}else if("department".equals(input)){
return o1.getDepartment().compareTo(o2.getDepartment());
}else if("rewardPoints".equals(input)){
return (o1.getRewardPoints() < o2.getRewardPoints()) ? -1 : ((o1.getRewardPoints() == o2.getRewardPoints()) ? 0 : 1);
}else if("salary".equals(input)){
return (o1.getSalary() < o2.getSalary()) ? -1 : ((o1.getSalary() == o2.getSalary()) ? 0 : 1);
}else{
return 0;// when proper field is not entered sorting will not happen
}
}
});
}else{
System.out.println("Please enter valid employee field to sort employee's...");
}
for(Employee alObj:al){
System.out.println("\n" + alObj.toString());
}
}

}

///员工类///

公共(public)类员工{

private long id;
private String name;
private String location;
private String department;
private int rewardPoints;
private double salary;

public Employee(long id, String name, String location, String department,
int rewardPoints, double salary) {
this.id = id;
this.name = name;
this.location = location;
this.department = department;
this.rewardPoints = rewardPoints;
this.salary = salary;
}

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getRewardPoints() {
return rewardPoints;
}
public void setRewardPoints(int rewardPoints) {
this.rewardPoints = rewardPoints;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", location="
+ location + ", department=" + department + ", rewardPoints="
+ rewardPoints + ", salary=" + salary + "]";
}

}

////根据tieTYT和radai的评论。我做了以下更改。如有错误请指正////

公共(public)类 GenericComparatorReflectionDemo {

static List<Employee> al = new ArrayList<Employee>();

static{
al.add(new Employee(45, "Vijay", "Bangalore", "Banking", 88, 99999));
al.add(new Employee(13, "Manoz", "Chennai", "Insurance", 48, 28000));
al.add(new Employee(79, "Ajay", "Hyderabad", "Real Estate", 54, 24000));
al.add(new Employee(21, "Sindu", "Noida", "Analyst", 89, 99998));
al.add(new Employee(67, "Honey", "Mumbai", "Social", 88, 111111));
al.add(new Employee(12, "Lucky", "Mysore", "Social", 86, 99997));
}

/**
* @param args
*/
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Please enter the field on which you want to sort employee's...");
final String input = scn.nextLine();
if(null != input && !"".equals(input)){
Collections.sort(al, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
try {
Field employeeField = Employee.class.getDeclaredField(input);
employeeField.setAccessible(true);
Comparable employeeFieldValue1 = (Comparable)employeeField.get(o1);
Comparable employeeFieldValue2 = (Comparable)employeeField.get(o2);
return employeeFieldValue1.compareTo(employeeFieldValue2);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
// when proper field is not entered sorting or any exception occurs
return 0;
}
}
});
}else{
System.out.println("Please enter valid employee field to sort employee's...");
}
for(Employee alObj:al){
System.out.println("\n" + alObj.toString());
}
}

}

最佳答案

这可能是主观的,因为我无法读懂面试官的想法。但如果我是你,我会使用反射来寻找领域。如果该字段是Comparable,则使用该接口(interface)。否则,您必须询问面试官您希望它如何在某些类型的领域发挥作用。

您的代码的问题在于它非常特定于当前类。如果添加新字段,除非您编写并编译新代码,否则它将无法对其进行排序。它也只适用于这个类。使用反射,您可以让它在几乎任何类上工作。

关于java - 有什么方法可以为列表中的对象字段编写通用排序代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26043509/

25 4 0
文章推荐: java - 如何将 List 转换为 List
文章推荐: Java 正则表达式输出