在`equals(T value)`中,T必须是Object,还是可以像City等?

发布于 2024-09-10 04:27:37 字数 561 浏览 14 评论 0 原文

我试图更好地理解 equals() 方法。我见过的所有示例都执行以下操作:

public class City
{
    public boolean equals(Object other)
    {
        if (other instanceof City && other.getId().equals(this.id))
        {
            return true;
        }

        // ...
    }
}

该方法必须采用对象而不是城市吗?

例如,下面的内容是不允许的吗?

public class City
{
    public boolean equals(City other)
    {
        if (other == null)
        {
            return false;
        }

        return this.id.equals(other.getId());
    }
}

I'm trying to understand the equals() method better. All examples I've seen do something like:

public class City
{
    public boolean equals(Object other)
    {
        if (other instanceof City && other.getId().equals(this.id))
        {
            return true;
        }

        // ...
    }
}

Must the method take on Object and not a City?

E.g. is this below not allowed?

public class City
{
    public boolean equals(City other)
    {
        if (other == null)
        {
            return false;
        }

        return this.id.equals(other.getId());
    }
}

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

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

发布评论

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

评论(3

困倦 2024-09-17 04:27:37

是的,它必须是一个对象。否则你就不会覆盖真实 Object#equals(),而是重载它。

如果您只是重载它,那么它不会被标准 API 使用,例如 Collection API等。

相关问题:

Yes, it must be an Object. Else you're not overriding the real Object#equals(), but rather overloading it.

If you're only overloading it, then it won't be used by the standard API's like Collection API, etc.

Related questions:

落在眉间の轻吻 2024-09-17 04:27:37

你可以两者兼得:(参见上面的 poke 评论)

public class City
{
    public boolean equals(Object other)
    {
        return (other instanceof City) && equals((City)other) ;
    }
    public boolean equals(City other)
    {
        return other!=null && this.id.equals(other.getId());
    }
}

you can have both: (see poke's comment above)

public class City
{
    public boolean equals(Object other)
    {
        return (other instanceof City) && equals((City)other) ;
    }
    public boolean equals(City other)
    {
        return other!=null && this.id.equals(other.getId());
    }
}
晨敛清荷 2024-09-17 04:27:37

如果您想重写 equals(),请不要使用 Object 以外的任何内容!

编写专门的 equals() 方法是一个常见错误,但往往会违反 equals() 约定。

Don't take anything else than an Object if you want to override equals()!

Writing a specialized equals() method is a common error but tends to violate the equals() contract.

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