问题
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.
回答1:
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
.
回答2:
Object does not implements comparable. You should crate MyObject which implements Comparable
interface.
class MyObject implements Comparable<Object>{
...
@Override
public int compareTo(Object arg0) {
// custom logic
return 0;
}
}
回答3:
- Well you can make that class implement java.lang.Comparable
Interface with Object
as Type Parameter
public class Test implements Comparable<Object>{
public int compareTo(Object o){
//
}
}
来源:https://stackoverflow.com/questions/13305940/abstract-object-comparison-in-java