简体   繁体   中英

Questions about implementing the Comparable interface

I am teaching a Java programming class for the first time. My textbook uses Comparable , but I see most examples on the net use Comparable<T> . Are these using two different interfaces?

Related to this, when I write a compareTo() method in my Student class, the textbook uses

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:

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> ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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