Obey the general contract when overriding equals

  看了effective java的遵守equal函数覆盖约定这一章,第一感觉是看英文原版太尼玛累了,这本书很多词都不会,虽然自认为英文能力还好,但是阅读起来还是有些勉强,不过再接再厉吧,这是我看的并发第一本书,看完这两本书自己以后看英文原版书就会顺畅多吧。发现英文原版比中文的要简略的多了,中文书太多废话了,不过看起来舒服。。。

  废话不多说了,把equals函数的精髓写下来吧:

1.对于override equals函数的类,不提倡使用继承,可以用组合代替(composition)

高质量equals函数餐谱:

1.Use the ==operator to check if the argument is a reference to this object.
If so, return true. This is just a performance optimization, but one that is worth
doing if the comparison is potentially expensive.
2.Use the instanceofoperator to check if the argument has the correct type.
If not, return false. Typically, the correct type is the class in which the method
occurs. Occasionally, it is some interface implemented by this class. Use an interface if the class implements an interface that refines the equalscontract to
permit comparisons across classes that implement the interface. Collection interfaces such as Set, List, Map, and Map.Entryhave this property.
3.Cast the argument to the correct type.Because this cast was preceded by an
instanceoftest, it is guaranteed to succeed.

4.For each “significant” field in the class, check if that field of the argument
matches the corresponding field of this object.
If all these tests succeed, return true; otherwise, return false. If the type in step 2 is an interface, you
must access the argument’s fields via interface methods; if the type is a class,
you may be able to access the fields directly, depending on their accessibility.

5.When you are finished writing your equalsmethod, ask yourself three
questions: Is it symmetric? Is it transitive? Is it consistent?

Tricks:

For primitive fields whose type is not float or double, use the == operator for comparisons;for object reference fields, invoke the equals method recuisively;for float fields, use the Float.compare method;and for double fields,use Double.compare.The special treatment of float and double fields is made necessary by the existence of FLOAT>NAN, -0.0f and the analogous double constants;For array fields,apply these guidelines to each element.If every element in an array field is significant,you can use one of ths Arrays.equals methods added in release 1.5

Some object reference fields may legitimately contain null. To avoid the possibility of a NullPointerException, use this idiom to compare such fields:
(field == null ? o.field == null : field.equals(o.field))
This alternative may be faster if fieldand o.fieldare often identical:
(field == o.field || (field != null && field.equals(o.field)))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值