compareTo和隐式类型转换的参数

时间:2013-01-04 13:44:23

标签: java

import java.util.*;

public class Employee
{
    private int empId;
    private String name;
    private int age;
    public Employee(String name, int id, int age )
    {
        this.name = name;
        this.empId = id;
        this.age = age;
    }
    public int getId()
    {
        return empId;
    }
    public int getAge()
    {
        return age;
    }
    public String getName()
    {
        return name;
    }

}

class SortById extends Employee implements Comparable<SortById>
{
    public SortById(String name, int id, int age)
    {
        super(name, id, age);
    }
    public int compareTo(SortById other)
    {
        if (this.getId() > other.getId()) return 1;
        if (this.getId() < other.getId()) return -1;
        return 0;

    }
}

class SortByName extends Employee implements Comparable<SortByName>
{
    public SortByName(String name, int id, int age)
    {
        super(name, id, age);
    }

    public int compareTo(SortByName other)
    {
        if (this.getName().compareTo(other.getName()) > 0) return 1;
        if (this.getName().compareTo(other.getName()) < 0) return -1;
        return 0;

    }
}

class Test
{
    public static void main(String args[])
    {
        Employee[] array = new SortById[3];
        array[0] = new SortById("Gautam", 1222, 20);
        array[1] = new SortById("Shivam", 1221, 20);
        array[2] = new SortById("Ankit", 1223, 21);
        System.out.println(array[0] instanceof SortByName);

        Arrays.sort(array);
        for (int i = 0; i < array.length; i++)
            System.out.println("ID: " + array[i].getId() + " Name: " + array[i].getName() + " Age: " + array[i].getAge());
        Employee[] array2 = new SortByName[3];
        array2[0] = new SortByName("Gautam", 1222, 20);
        array2[1] = new SortByName("Shivam", 1221, 20);
        array2[2] = new SortByName("Ankit", 1223, 21);
        Arrays.sort(array2);
        for (int i = 0; i < array2.length; i++)
            System.out.println("ID: " + array2[i].getId() + " Name: " + array2[i].getName() + " Age: " + array2[i].getAge());

    }
}

这个程序运行正常,我只是想问一下,因为我使用参数化版本的Comparable,我引用compareTo的引用应该是SortById类型还是{ {1}}类型?

即使引用的类型为SortByName,代码仍可正常运行,但指向其子类(EmployeeSortByName)。

如何发生隐式演员?我读过是不可能的,也就是说,不可能隐式地将超类类型转换为子类。

1 个答案:

答案 0 :(得分:2)

您永远不会致电compareTo,这解释了您不需要演员表的原因。实际调用在Arrays.sort范围内处理(通过实际使用原始Comparable

此外,在这种情况下,编译器将生成2个compareTo方法:您使用SortByXX参数明确定义的方法,以及另一个具有Object参数的方法,该方法委派给第一个。

正如@martijno所说,如果你在数组中添加一个简单的Employee,你会遇到问题,这会导致ClassCastException(从EmployeeComparable }或SortByXX)。如果您混合使用SortByNameSortById,则会出现相同的情况。