gpt4 book ai didi

java - 如何在java中对包含两个以上异构对象的List进行排序?

转载 作者:行者123 更新时间:2023-11-29 08:26:04 25 4
gpt4 key购买 nike

您好,我有一个对象列表,其中包含四个对象(员工、学生、患者、客户)。我需要根据相应的 ID 对这些列表进行升序排序。当我使用 Collections.sort(list) 方法时出现 ClassCastException

下面是我正在使用的完整代码...

注意:我也尝试过使用Comparator 接口(interface),但无法在compare() 方法中定义逻辑来对这些进行排序目的。如果列表包含两个对象,那么很容易在内部定义对这些对象进行排序的逻辑,但如果列表包含两个以上的对象,则很难在 compare() 方法中定义排序逻辑。

任何人都可以帮我缩短这个列表吗?请修改以下代码并为我提供解决方案。输出应按 [10,20,30,40,50,60,70,90] 的排序顺序

public class Test
{
public static void main(String[] args)
{
List list = new ArrayList();
list.add(new Employee(50));
list.add(new Customer(10));
list.add(new Patient(60));
list.add(new Student(90));
list.add(new Employee(20));
list.add(new Customer(40));
list.add(new Patient(70));
list.add(new Student(30));

Collections.sort(list);
System.out.println(list);

}
}

class Patient implements Comparable<Patient>
{

int pId;

Patient(int pId)
{
this.pId = pId;
}

@Override
public int compareTo(Patient o)
{
return this.pId - o.pId;
}

@Override
public String toString()
{
return this.pId + "";
}

}

class Employee implements Comparable<Employee>
{

int empId;

Employee(int empId)
{
this.empId = empId;
}

@Override
public int compareTo(Employee o)
{
return this.empId - o.empId;
}

@Override
public String toString()
{
return this.empId + "";
}

}

class Customer implements Comparable<Customer>
{

int cId;

Customer(int cId)
{
this.cId = cId;
}

@Override
public int compareTo(Customer o)
{
return this.cId - o.cId;
}

@Override
public String toString()
{
return this.cId + "";
}

}

class Student implements Comparable<Student>
{

int sId;

Student(int sId)
{
this.sId = sId;
}

@Override
public int compareTo(Student o)
{
return this.sId - o.sId;
}

@Override
public String toString()
{
return this.sId + "";
}

}

最佳答案

定义接口(interface)Identifiable (或父类(super class) Person),方法为 int getId() .

让所有的类都实现该接口(interface)(或扩展该父类(super class))。

停止使用原始类型,因此使用 List<Identifiable>而不是 List .

然后使用 Comparator<Identifiable> 对列表进行排序,可以使用 Comparator.comparingInt(Identifiable::getId) 定义.

您的所有类都不应该实现 Comparable。他们的 ID 没有定义他们的自然顺序。在这个特定用例中,您只是碰巧按 ID 对它们进行排序。因此应该使用特定的比较器。

关于java - 如何在java中对包含两个以上异构对象的List进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53020277/

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