简体   繁体   English

重载未按预期运行

[英]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 2 compareTwo methods for my Client class.我的客户端 class 有 2 个 compareTwo 方法。 One to compare the client to another client, and one to compare it to an int.一个用于将客户端与另一个客户端进行比较,另一个用于将其与 int 进行比较。 Client Should be of the type comparable because it's inside a tree structure that implements Comparable. Client 应该是可比较的类型,因为它位于实现 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.每次调用此 function 时,它都会使用 compareTo(Object) 方法并返回无法将我的 int 强制转换为客户端的错误。 I suppose this is because Object is a superclass of int(?) but don't quite know how to fix it.我想这是因为 Object 是 int(?) 的超类,但不太知道如何解决它。 I tried working around the problem, but can not seem to fix it without changeing my entire code.我尝试解决这个问题,但似乎无法在不更改我的整个代码的情况下解决它。

Thanks for your help!谢谢你的帮助!

Java's TreeMap and TreeSet use the compareTo(T) method (ie, for raw types like you seem to be using, compareTo(Object) , so your overloaded method is just ignored. Java 的TreeMapTreeSet使用compareTo(T)方法(即,对于您似乎正在使用的原始类型, compareTo(Object) ,因此您的重载方法将被忽略。

While you can, of course, overload the compareTo method, you can't force Java's data structures to use it.当然,您可以重载compareTo方法,但不能强制 Java 的数据结构使用它。

One possible approach could be to have the compareTo(Object) method check the type dynamically:一种可能的方法是让compareTo(Object)方法动态检查类型:

//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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM