import java.util.ArrayList;
import java.util.*;
class Employee1 implements Comparable<Employee1> {
int empno;
String name;
Employee1(int i,String j) {
empno=i;
name=j;
}
public int compareTo(Employee1 e1) {
Employee1 e2=this;
Integer i1=e1.empno;
Integer i2=e2.empno;
return i1.compareTo(i2);
}
}
public class Employee {
public static void display(ArrayList<Employee1> i) {
for(Employee1 o:i){
System.out.println(o.empno);
}
}
public static void main(String[] args) {
ArrayList<Employee1> ob=new ArrayList<Employee1>();
Employee1 e1=new Employee1(1001,"A");
Employee1 e2=new Employee1(1002,"B");
ob.add(e2);
ob.add(e1);
Collections.sort(ob);
display(ob);
}
}
输出应该是1001 1002
,而不是输出是1002 1001
。
首先我将e2
对象传递empno
给列表,然后
传递e1
给empno
1001
由于-中的compareTo
方法应该与所以为什么它们以错误的顺序显示?Employee1
e1.compareTo(e2);
1001.compareTo(1002);