简体   繁体   中英

Java Generic syntax with Comparable interface

I am trying to implement a simple insertion sort algorithm and make it generic to all the instance of Comparable interface.

public static <E extends Comparable<E>> void InsertionSort( E [] array)
{
    for(int i = 1; i < array.length; i++)
    {
        E current = array[i];

        int k;
        for(k = i-1; k >= 0 && current.compareTo(array[k]) < 0 ; k--)
        {
            array[k+1] = array[k];

        }

        array[k+1]=current;

    }

    for(int l = 0; l < array.length; l++)
    {
        System.out.print(array[l]+" ");

    }

    System.out.println();
}

The problem I have is I don't know the differences between

 <E extends Comparable<E>>

and

 <E extends Comparable>

They both work but I don't know the reason for the first one.

E extends Comparable<E> means that an instance of E can be compared to other objects of type E .

E extends Comparable means that an instance of E can be compared to...something. It's a raw type, which is bad. Don't do that.

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