Search code examples
javaobjectcompareto

How to compare two objects without knowing their type


I'm implementing a sorted list class , in this class i'm going to sort any kind of objects , so now i want to test if the object is comparable or not ,

i used this code to override the compareTo() method :-

class MyObject implements Comparable {

Object ob;

    MyObject(){
        this.ob=new Object();
    }

    public int compareTo(Object current){
        if((ob.toString().compareTo(current.toString()))>1)
        return 1;
        else if((ob.toString().compareTo(current.toString()))<1)
        return -1;
        else
        return 0;

    }

    public String toString(){

        return (String)ob;
    }
}

so now i need to assign numbers to these objects like this

class SortedListTest{
    public static void main (String arg[]){

        MyObject b1= new MyObject();
        MyObject b2= new MyObject();

        b1.ob=6;
        b2.ob=3;

        System.out.println(b2.compareTo(b1));
    }

}

but it keeps giving me this exception:-

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String


Solution

  • The problem you're reporting is that

    return (String)ob;
    

    should be

    return ob.toString();
    

    if ob is never null; or

    return Objects.toString(ob);
    

    if it might be.


    But note that wrapping an object in an object to compare its toString() isn't necessary. You can simply use a Comparator<Object>, like Guava's Ordering.usingToString():

    int order = Ordering.usingToString().compare(someObject, someOtherObject);
    

    or whatever the Java 8 equivalent is. I guess it would be something like:

    Comparator<Object> usingToString = (a, b) -> a.toString().compareTo(b.toString());
    int order = usingToString(someObject, someOtherObject);