Search code examples
javaclasscomparable

Make java class Comparable to 2 different Classes


I would like to implement the Comparable Interface "Twice"

public class Segment implements Comparable<Segment,Point>{
@Override
public int compareTo(Segment o) {
    return 0;
}
@Override
public int compareTo(Point p) {
    return 0;
}

Is it possible in some way? (Without using the generic interface compareTo(Object o) i think it's nasty...)


Solution

  • Why dont you try this way

    public class Segment implements Comparable<Object>{
         @Override
         public int compareTo(Object o) {
             if(o instanceof Segment)
             {
                  return 0;
             }
             else if(o instanceof Point)
             {
                 return 0;
             }
    
         }
    }
    

    Well if you really want to do it in your way, then you can just add another method using overloading (without adding the @Override annotation).

    public class Segment implements Comparable<Segment>{
        @Override
        public int compareTo(Segment o) {
            return 0;
        }
    
        public int compareTo(Point p) {
           return 0;
        }
    }
    

    It will be useful if you call the compareTo method manually. I am not sure what will happen they called from some other library methods.