Abstract Object Comparison in Java

怎甘沉沦 提交于 2019-12-13 06:31:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!