-2
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给列表,然后 传递e1empno1001

由于-中的compareTo方法应该与所以为什么它们以错误的顺序显示?Employee1e1.compareTo(e2);1001.compareTo(1002);

4

2 回答 2

1

改变

  return i1.compareTo(i2);

  return -i1.compareTo(i2);

或者

  return i2.compareTo(i1);
于 2013-04-01T12:00:16.767 回答
0

我认为您的代码写得不好。

以下是该方法的编码方式:

public int compareTo(Employee1 other) {
    return this.empno.compareTo(other.empno);
}
于 2013-04-01T11:59:19.787 回答