Search code examples
javaclasscastingoverloadingcompareto

Overloading not behaving as expected


I am making a Hotel where my clients are stored in a tree structure so they can be easily searched.

I have two compareTo methods for my Client class. One to compare the Client to another Client, and one to compare it to an int. Client should be of the type Comparable because it's inside a tree structure that implements Comparable.

//compare Client to int
public int compareTo(int arg0) {
    int result = this.clientId.compareTo(arg0);
    return result;
}

//compare Client to object
public int compareTo(Object o) {
    return (this.clientId).compareTo(((Client)o).clientId);
}

But it does not have the desired effect. Every time this function gets called, it uses the compareTo(Object) method and returns an error that my int can't be cast to Client. I suppose this is because Object is a superclass of int(?) but don't quite know how to fix it. I tried working around the problem but can not seem to fix it without changing my entire code.


Solution

  • Java's TreeMap and TreeSet use the compareTo(T) method (i.e., for raw types like you seem to be using, compareTo(Object), so your overloaded method is just ignored.

    While you can, of course, overload the compareTo method, you can't force Java's data structures to use it.

    One possible approach could be to have the compareTo(Object) method check the type dynamically:

    //compare Client to object
    public int compareTo(Object o) {
        Integer toCompare;
        if (o instanceof Client) {
            toCompare = ((Client) o).clientId;
        } else if (o instanceof Integer) {
            toCompare = (Integer) o;
        } else {
            throw new IllegalArgumentException();
        }
    
        return (this.clientId).compareTo(toCompare);
    }