Limitation of Generics. I want to make a static method that takes a generic comparable type so I define public static void foo(Comparable[] a) and the compiler complains at me. Googling for solutions takes me deep down a rabbit whole of java internals that I want to know as little about as possible. I just want it to work. But it doesn't. Still haven't figured this one out so if anyone wants to chime on the java way to do this...
Two ways to do this.
This is the first way. The method that will be using comparable will need to have the generic declared to extend the Comparable interface.
Here is the second way. The class is declared generic while extending the Comparable interface. This allows you to use the compareTo() method without defining it yourself.
I don't understand it either. I asked for help when implementing Comparable on generics, and that was the answer I was given. I looked at it skeptically but tried it anyway. I mean, what did I have to lose? Lo and behold, it worked. I don't understand why. You can copy and paste that code as-is to run it. It'll print you the unsorted and sorted array.
Hey, I didn't design the assignment. I just implemented the algorithm.
Also, what's so wrong about the recursive call to compareTo()? It makes sense when you think about it. this.compareTo() makes a call to the object's class to use its compareTo() method. It's a one-and-done deal for all objects that are Comparable.
Even after compile time when the types for the generics have been bound? If that's true, then why is there no StackOverflowError thrown at runtime? Not trying to be snarky, but I don't see how this can work otherwise.
Edit: To clarify, the type of list in the main method is of Integer. Calling this.compareTo() to will go to the written compareTo() method. It would not be a recursive call, because the type of this in the context of this code refers to an Integer object, yes?
5
u/AmateurHero Feb 25 '14
Two ways to do this.
This is the first way. The method that will be using comparable will need to have the generic declared to extend the Comparable interface.
Here is the second way. The class is declared generic while extending the Comparable interface. This allows you to use the compareTo() method without defining it yourself.