Collections.sort - 我创建了2个用户定义对象[两者都是不同类型]然后添加到arraylist中,然后我尝试对它进行排序

时间:2015-01-14 20:25:44

标签: java sorting collections

  

预期的代码结果是ClassCastException但实际结果: - [pid-1-a1-name,pid-2-c2-name,Sorting.Employee @ cdfc9c,Sorting.Employee @ 1837697]

Person上课:

package Sorting;

public class Person implements Comparable<Person> {
    private int pid;
    private String pname;

    public int getPid() {
        return pid;
    }

    public void setPid(int pid) {
        this.pid = pid;
    }

    public String getPname() {
        return pname;
    }

    public void setPname(String pname) {
        this.pname = pname;
    }

    @Override
    public String toString() {
        return "Person with pid- " + getPid() + " - " + getPname(); 
    }

    @Override
    public int compareTo(Person p) {
        return this.pid - p.pid;
    }
}

Employee上课:

package Sorting;

public class Employee implements Comparable {
    @Override
    public int compareTo(Object o) {
        return 0;
    }
}

SortingofObjects上课:

package Sorting;

import java.util.ArrayList;
import java.util.Collections;

public class SortingofObjects {

    public static void main(String[] args) {
        Person p1 = new Person();
        p1.setPid(1);
        p1.setPname("a1-name");

        Person p2 = new Person();
        p2.setPid(2);
        p2.setPname("c2-name");
        Employee e1 = new Employee();
        Employee e2 = new Employee();

        ArrayList a = new ArrayList();
        a.add(p1);
        a.add(p2);
        a.add(e1);
        a.add(e2);
        Collections.sort(a);
        System.out.println(a);
    }
}

2 个答案:

答案 0 :(得分:2)

Collections.sort不会在compareTo中的每一对上调用List,只需要足够的对来对List进行排序。例如,运行以下代码:

public class Test implements Comparable<Test> {

    public static void main(String[] args) {
        List<Test> list = new ArrayList<Test>();
        list.add(new Test(1));
        list.add(new Test(2));
        list.add(new Test(3));
        list.add(new Test(4));
        Collections.sort(list);
    }

    private final int number;

    Test(int number) {
        this.number = number;
    }

    @Override
    public int compareTo(Test that) {
        System.out.println(this + ".compareTo(" + that + ")");
        return 0;
    }

    @Override
    public String toString() {
        return "" + number;
    }
}

输出

2.compareTo(1)
3.compareTo(2)
4.compareTo(3)

由于您的List符合PersonPersonEmployeeEmployee的顺序,因此唯一会引发ClassCastException的组合,即

Person.compareTo(Employee) 

永远不会发生。如果您的ListEmployee之前包含Person,则会引发异常。

答案 1 :(得分:0)

如果碰巧使用的排序算法只将Employee s与Person s进行比较,而不是相反,则它永远不会抛出,因为{{1} }接受任何Employee.compareTo。你或多或少都很幸运。