对于不同的对象,使用多个instanceof测试覆盖equals()是否可行?

发布于 2024-12-12 09:09:26 字数 390 浏览 0 评论 0原文

假设我有一个类,我必须检查多种不同类型的对象。通过以下方式重写 equals() 是否可行/可能?

public boolean equals(Object o){
    if(o == null) return false;
    if(o instanceof class1){
        return this.class1.equals((class1) o);
    if(o instanceof class2){
        return this.class2.equals((class2) o);
    ...

}

这会有用吗?我在这里假设我在相应的类中创建了一个静态重载的 equals() 方法(尽管只要我进行强制转换,多态性可能会自动处理这个问题?)。

Say I have a class where I would have to check for multiple different types of objects. Would it be feasible/possible to override equals() in the following manner?

public boolean equals(Object o){
    if(o == null) return false;
    if(o instanceof class1){
        return this.class1.equals((class1) o);
    if(o instanceof class2){
        return this.class2.equals((class2) o);
    ...

}

Would this ever be useful? I assume here that I create a static overloaded equals() method in the respective classes (though maybe polymorphism would take care of that automatically as long as I cast?).

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

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

发布评论

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

评论(4

谎言 2024-12-19 09:09:46

如果您确定它不会导致相互递归,您可以返回that.equals(this)。然而,一般来说,对象平等意味着类的平等,或者至少是它们之间一致的继承关系。

If you're sure that it won't lead to mutual recursion you can just return that.equals(this). However in general object equality implies either equality of classes, or at least a coherent inheritance relationship between them.

千纸鹤带着心事 2024-12-19 09:09:44

从语义上讲,我认为这不是一个好主意。等于不应该基于类类型,而应该基于实例变量。
除此之外,苹果永远不应该等于梨,而只能等于其他苹果。

Semantically I don't think this is a good idea. Equals should not be based on class types but instance variables.
Apart from that, an Apple should never be equal to a Pear but only to other apples.

挽手叙旧 2024-12-19 09:09:41

似乎您想要一种方法来检查指定对象是否等于接收器中的各种成员变量中的至少一个。

覆盖 java.lang.Object#equals 用于此目的。

您应该提供不同的方法,例如

public boolean hasEquals(Object o) { // your impl }

It seems like you want a method to check whether a specified object is equal to at least one of various member variables in the receiver.

It is inappropriate to override java.lang.Object#equals for this purpose.

You should instead provide a different method, e.g.

public boolean hasEquals(Object o) { // your impl }
左秋 2024-12-19 09:09:38

我非常怀疑,因为这样很容易违反 equals 的传递性(x.equals(y) && x.equals(z) 暗示 y.equals(z)

当然,除非你做了一个涉及所有类的非常全面的设置,但这将是一个痛苦的正确方法

I very much doubt that because you can easily violate the transitivity of equals this way (x.equals(y) && x.equals(z) implies y.equals(z))

unless of course you do a very throughout setup involving all classes but that would be a pain to get right

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