Obey the general contract when overriding equals

来源:互联网 发布:input file网络图片 编辑:程序博客网 时间:2024/06/07 08:30

  看了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 aninterface, 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
原创粉丝点击