Search code examples
javagenericscomparable

What am I accomplishing using generics?


I have the following code block:

public static void main(String[] args) {
    Integer[] test = new Integer[100];
    comparableTest(test);
    genericsTest(test);
}

private static void comparableTest(Comparable[] c) {

}

private static <E extends Comparable<E>> void genericsTest(E[] e) { }

What exactly am I accomplishing using the generics? These both have no compile errors. I can still use the compareTo method. So what am I gaining using E extends Comparable<E> instead of just using Comparable?

The context for this question is that I am making sorting algorithms use the E extends Comparable<E> instead of Comparable.


Solution

  • Explanation

    • Without the generics you could get a class that is not comparable to itself but to other things. Like an A implements Comparable<B>, this is unusual but possible.

    • Also, you just lose type safety on the compareTo, as it then falls back to accepting Objects. So you could accidentally make a mistake, passing the wrong thing and Java can not help you and prevent it.

    For real, there is no reason why you should ever consider using raw types (dropping the generics) if you are not forced to develop for earlier than Java 5.


    Example

    An example, considering your snippet, you pass Integer[] into it. An Integer can not be compared to Dogs. So if you accidentally do something stupid like:

    Dog dog = new Dog();
    if (c[0].compareTo(dog) == 0) { ... }
    

    This will actually compile with the variant that takes Comparable[], but crash on runtime when you execute it. The other variant is able to detect this bug at compile-time and generally help you spot your mistake much earlier, which is good.

    This example may look contrived but stuff like that can happen really quick.


    Note

    You might want to consider renaming your c to something that helps readability. Someone reading a c might not know what it represents in your case, maybe it stands for a character, maybe a car.

    In general, try to avoid abbreviating. What about comparables, elements or items.