对于不同的对象,使用多个instanceof测试覆盖equals()是否可行?
假设我有一个类,我必须检查多种不同类型的对象。通过以下方式重写 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您确定它不会导致相互递归,您可以返回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.从语义上讲,我认为这不是一个好主意。等于不应该基于类类型,而应该基于实例变量。
除此之外,苹果永远不应该等于梨,而只能等于其他苹果。
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.
似乎您想要一种方法来检查指定对象是否等于接收器中的各种成员变量中的至少一个。
覆盖 java.lang.Object#equals 用于此目的。
您应该提供不同的方法,例如
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.
我非常怀疑,因为这样很容易违反 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)
impliesy.equals(z)
)unless of course you do a very throughout setup involving all classes but that would be a pain to get right