如何在java中对包含两个以上异构对象的列表进行排序?
嗨,我有一个对象列表,其中包含四个对象(员工、学生、患者、客户)。我需要根据这些列表对应的ID按升序对它们进行排序。
当我使用Collections.sort(list)
时,方法给出ClassCastException
下面是我正在使用的完整代码
注意:我也尝试了Comparator
接口,但无法在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 + "";
}
}
# 1 楼答案
使用方法
int getId()
定义接口Identifiable
(或超类Person)让你的所有类实现这个接口(或者扩展那个超类)
停止使用原始类型,因此使用
List<Identifiable>
而不是List
然后使用
Comparator<Identifiable>
对列表进行排序,可以使用Comparator.comparingInt(Identifiable::getId)
来定义您的所有类都不应该实现可比性。他们的ID不定义他们的自然顺序。在这个特定的用例中,您只是碰巧按ID对它们进行了排序。因此应该使用特定的比较器
# 2 楼答案
创建类,比如具有id属性的person。然后通过它扩展所有这些课程。然后只需要为person类编写比较
# 3 楼答案
只需为所有POJO添加一个公共接口,定义一个获取id的方法,然后编写一个用于比较的自定义比较器,就可以轻松完成这项工作
这是对对象进行排序的重写版本
现在自定义比较器:
通用对象接口:
经过测试,以上代码的输出如下:
谢谢,欢迎提出任何建议
# 4 楼答案
定义一个超类,例如
Person
,并在那里添加id
。基于id逻辑的比较也应该在那里实现使所有基类从
Person
扩展在
Person
上定义List
并对其应用排序