java泛型类中的equals方法

发布于 2024-12-18 03:36:18 字数 277 浏览 2 评论 0原文

我有一个名为 ArrayBag 的通用类。我想重写 equals 方法。所以我写了

public boolean equals(T other){

} // gives error
<块引用>

错误消息:名称冲突:ArrayBag 类型的方法 equals(T) 与 Object 类型的 equals(Object) 具有相同的擦除功能,但没有 覆盖它

I hava a generic class called ArrayBag. I want to override equals method. So i wrote

public boolean equals(T other){

} // gives error

error message: Name clash: The method equals(T) of type ArrayBag has the same erasure as equals(Object) of type Object but does not
override it

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

三生池水覆流年 2024-12-25 03:36:18

您尝试重写的 equals 方法需要一个 Object。当您的代码转换为字节代码时,类型擦除会将您的 T 转换为 Object,这与现有的 equals 方法冲突。

@Override
public boolean equals(Object other) {
    if (other instanceof T)
    {
        T o = (T) other;
        ...
    }
}

在该方法内部,您可以处理对 T 的转换。

The equals method you are trying to override expects an Object. When your code is translated to byte code, type erasure transforms your T into an Object, which conflicts with the existing equals method.

@Override
public boolean equals(Object other) {
    if (other instanceof T)
    {
        T o = (T) other;
        ...
    }
}

Inside the method you can handle casting to T.

淑女气质 2024-12-25 03:36:18

equals(T other) 替换为 equals(Object other),然后在方法内将 other 转换为 T执行。

public boolean equals(Object other)
{
    T t = (T) other;
    // ...
}

Replace equals(T other) with equals(Object other), and then cast other to T inside the method implementation.

public boolean equals(Object other)
{
    T t = (T) other;
    // ...
}
谁对谁错谁最难过 2024-12-25 03:36:18

你需要这个。

public boolean equals(Object other){
      T t = (T) other;

}

you need this.

public boolean equals(Object other){
      T t = (T) other;

}
记忆里有你的影子 2024-12-25 03:36:18

任何时候需要重写方法时,签名都必须与要重写的方法相同。因此,您必须将 Object 作为唯一的参数传递给 equals 方法,以便它能够按需要运行。

作为 Grantham 可靠解决方案的替代方案,您可以使用 getClass() 代替 instanceof,例如,如果您计划扩展泛型类并且不希望子类实例等于您的超类实例。

那看起来像:

@Override
public boolean equals(Object other) {
    if (other != null && getClass() == other.getClass()) {
        T o = (T) other;

        // ...

    }
    return false;
}

Any time you need to override a method, the signature must be the same as the method to be overriden. Therefore you must pass Object as the one and only argument to your equals method for it to function as desired.

As an alternative to Grantham's solid solution, you can use getClass() in place of instanceof, if for example you plan on extending your generic class and don't want sub class instances to ever equal your super class instances.

That would look like:

@Override
public boolean equals(Object other) {
    if (other != null && getClass() == other.getClass()) {
        T o = (T) other;

        // ...

    }
    return false;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文