Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparable<T> vs Raw Comparable

I was recently writing a simple generic selection sort method for the fun of it, when I got a little confused about something. Here's my code:

public static <T extends Comparable<T>> void sort(List<T> list) {
    for (int i = 0; i < list.size(); i++) {
        int minIndex = i; // Assume that the first element is the minimum for now.

        // Find smallest element in unsorted sub-list.
        for (int k = i + 1; k < list.size(); k++) {
            if (list.get(k).compareTo(list.get(minIndex)) < 0) {
                minIndex = k;
            }
        }

        // Swap smallest element with the first element in unsorted sub-list.
        T temp = list.get(i);
        list.set(i, list.get(minIndex));
        list.set(minIndex, temp);
    }
}

The function itself works fine, but I got a little confused about the generics. I use:

<T extends Comparable<T>>

to ensure that the given List has a comparable type. But what if I were to use a raw Comparable instead? That is:

<T extends Comparable>

What exactly would be the repercussions?

Thanks!

like image 237
Decoy Avatar asked Dec 20 '22 02:12

Decoy


1 Answers

Basically, you lose some type safety.

When you have your T temp = list.get(i), what can you do with temp.compareTo?

  • with T extends Comparable<T>, temp is Comparable<T>, meaning you can only pass another T into compareTo
  • with T extends Comparable, temp is Comparable, meaning you can pass anything into compareTo

The first of those is almost definitely what you want, because comparable types can only handle objects of the same type. For instance, String.compareTo can only handle String inputs -- if you pass in an Integer, you'll get a ClassCastException.

Given that the only safe input to temp.compareTo is a reference of type T, there is usually no good reason to use the raw type. It's occasionally beneficial for getting around the type system, but in most cases it removes type safety without giving you anything in return.

like image 125
yshavit Avatar answered Jan 03 '23 16:01

yshavit