有关实现Comparable接口的问题

时间:2014-01-31 17:59:38

标签: java comparable

我是第一次教Java编程课程。我的教科书使用了Comparable,但我看到网上使用Comparable<T>的大多数示例。这些是使用两种不同的接口吗?

与此相关,当我在Student类中编写compareTo()方法时,教科书使用

public int compareTo(Object other){
    if (! (other instance of Student))
        throw new IllegalArgumentException("Parameter must be a Student");
    return name.compareTo( ((Student)other).getName() );
}

我看到compareTo()的其他示例如下:

public int compareTo(Student otherStudent){
    return name.compareTo( otherStudent.getName() );
}

如果Student类实现Comparable<Student>

,这是第二个构造应该使用的构造吗?

最后,我的教科书给出了如何编写通用对象排序算法的提示。我到了以下地方。它可以工作,但会发出“未经检查或不安全的操作”警告。有没有办法编写“安全”的通用排序算法?

private static void bubbleSortObjects(Comparable[] array)
{
    int i = 0;
    boolean swapped = true;
    while (swapped && i < array.length - 1)
    {
        i++;
        swapped = false;
        for (int j = 0; j < array.length - i; j++)
        {
            if (array[j].compareTo(array[j + 1]) > 0)
            {
                Comparable temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
                swapped = true;
            }
        }
    }
}

感谢您提供任何帮助或建议。

1 个答案:

答案 0 :(得分:1)

只是寻求帮助,现代通用排序算法将是:

private static <T extends Comparable<? super T>> void bubbleSortObjects(T[] array)
{
    int i = 0;
    boolean swapped = true;
    while (swapped && i < array.length - 1)
    {
        i++;
        swapped = false;
        for (int j = 0; j < array.length - i; j++)
        {
            if (array[j].compareTo(array[j + 1]) > 0)
            {
                T temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
                swapped = true;
            }
        }
    }
}   
相关问题