覆盖等于方法 [英] Override equals method

查看:121
本文介绍了覆盖等于方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的新手问题:

因此,在我的大学作业中,我必须为我创建的新类重写对象类的equals方法.

So in my university homework I have to override the object class equals method for a new class created by me.

新类是产品",每个产品都有一个唯一的"id"属性.所以这就是我覆盖它的方式:

The new class is "Product", each product has an "id" attribute which is unique. So this is how I Overrided it:

@Override
public boolean equals(Object obj) {
       final Product other = (Product) obj;
       if (id != other.id)
           return false;
       return true;
   }

问题是这样做的满分是10分,满分为1,5分,这让我感到怀疑.所以我开始搜索,发现了以下内容:

The thing is that doing this is 1,5 points out of 10 and it made me suspicius to be that easy. So i started searching and I found things like:

@Override
public boolean equals(Object obj) {
       if (this == obj)
           return true;
       if (obj == null)
           return false;
       if (getClass() != obj.getClass())
           return false;
       final Product other = (Product) obj;
       if (id != other.id)
           return false;
       return true;
   }

这对我完全没有意义,因为我认为最后一个if检查所有其他ifs限制.你们是怎么想的?哪种是重写此方法的更好方法?

Which don't make sense for me at all, because I think that the last if check all the other ifs restrictions. What do you guys think?Which is the better way to Override this method?

谢谢!

推荐答案

第二段代码更好:

  • 它针对x.equals(x)进行了优化,对于正确性而言这不是必需的,但它是有用的优化方法
  • 它处理x.equals(null)而不是抛出NullPointerException
  • 它处理完全不同类的对象,而不会抛出您所要的ClassCastException(例如x.equals("foo"))
  • 它需要 exact 相同的类型才能提供对称关系;否则obj.equals(x)可以调用不同的方法,从而得到不同的结果.
  • It optimizes for x.equals(x), which isn't necessary for correctness, but is a helpful optimization
  • It copes with x.equals(null) instead of throwing NullPointerException
  • It handles objects of a completely different class without throwing a ClassCastException which yours would (e.g. x.equals("foo"))
  • It requires the exact same type to provide a symmetric relationship; otherwise obj.equals(x) could invoke a different method, giving a different result.

这篇关于覆盖等于方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆