简体   繁体   English

有关实现Comparable接口的问题

[英]Questions about implementing the Comparable interface

I am teaching a Java programming class for the first time. 我是第一次教Java编程课程。 My textbook uses Comparable , but I see most examples on the net use Comparable<T> . 我的教科书使用Comparable ,但是网上看到的大多数示例都使用Comparable<T> Are these using two different interfaces? 它们是否使用两个不同的接口?

Related to this, when I write a compareTo() method in my Student class, the textbook uses 与此相关的是,当我在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() );
}

I see other examples of compareTo() like this: 我看到如下的compareTo()的其他示例:

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

Is this second construct what one should use if the Student class implements Comparable<Student> ? 如果Student类实现Comparable<Student>这第二种构造应该使用什么?

Finally, my textbook gives hints on how to write a general-purpose object sorting algorithm. 最后,我的教科书提供了有关如何编写通用对象排序算法的提示。 I arrived at the following. 我到达以下。 It works, but gives "unchecked or unsafe operations" warning. 它可以工作,但是会发出“未经检查或不安全的操作”警告。 Is there a way to write a "safe" general-purpose sorting algorithm? 有没有一种方法可以编写“安全”的通用排序算法?

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;
            }
        }
    }
}

Thanks for any help or advice. 感谢您的帮助或建议。

Just for help, a modern general purpose sorting algorithm would be: 仅出于帮助,现代通用排序算法将是:

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;
            }
        }
    }
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM