Java中的抽象对象比较 [英] Abstract Object Comparison in Java
问题描述
我正在为抽象对象实现堆。
现在我能够实现一个堆栈,因为不需要比较堆栈。
但是堆需要比较。
所以我有对象A
和对象B
。我可以确保堆
中的 Object
是同一类,并且可以对其进行排序(那是该类具有 compareTo
函数来了解如果A< B,A = B或A> B)
。
但是如果我使用 A.compareTo(B)
,则会收到语法错误,指出 compareTo
是没有为对象定义。
我做了一些研究,发现Object没有实现Comparable。
我该如何解决这个问题。
谢谢。
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.
推荐答案
如果所有对象都是实现了<$ c $的共同祖先的后代,该怎么办? c>可比?因此,在这种情况下,您可以在代码中使用该类型,而不是 Object
。
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
.
这篇关于Java中的抽象对象比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!