Search code examples
javaobjectabstract-classcomparable

Abstract Object Comparison in Java


I am implementing a heap for abstract objects. Now I was able to implement a stack as there are no comparisons required for a Stack. However the heap requires comparisons. So I have Object A, and Object B. I can ensure that the Object that are in the heap are of the same class, and that they can be ordered (that is the class has a compareTo function to know if A<B, A=B, or A>B). But if I use A.compareTo(B), I get a syntax error saying that compareTo is not defined for objects. I did some research and found that Object does not implement Comparable. How can I go about this problem. Thank you.


Solution

  • What if all your objects were descendants of a common ancestor which do implement Comparable? So in that case you could use that type in your code not Object.