- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我有一个对象列表,其中包含四个对象(员工、学生、患者、客户)。我需要根据相应的 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/
我有一个 NSTreeController (向 NSOutlineView 提供内容)。我希望顶级对象属于一个类,而所有其他对象(因此,任何级别的子对象)属于另一个类。解决这个问题的最佳方法是什么?
我有一个如下所示的 GADT data MyTypes = MyInt | MyDouble data Test (t :: MyTypes) where A :: Int -
我需要一个高效的异构数组,其中第一个元素是 int,其余是 float。然而,创建它之后,基本的数组操作就会呈爆炸式增长。 A = np.zeros(1, dtype='i4, f4, f4') B
我有一个 pandas DataFrame,其中包含需要拆分成平衡切片的字符串和浮点列,以便训练 sklearn 管道。 理想情况下,我会使用 StratifiedKFold在 DataFrame 上
是否有一种异构容器的形式,能够存储例如不同的基本类型(例如int、float、double)? 最终我希望能够在计算中使用元素而无需显式引用类型,例如 auto res = a + b,其中操作数 a
假设我有一个结构(或类),如下所示: struct _particle { std::vector vx , vy; std::vector id; std::vector rx, ry; }; ty
我在将具有 > 22 列的表专门映射到 case class 时遇到问题,假设您有以下代码 import slick.driver.PostgresDriver import scala.slick.
我是一名优秀的程序员,十分优秀!