How to implement equals () and Hashcode () methods in java[reproduced]

Source: Internet
Author: User

Part I:
equals () (javadoc) must define an equivalence relation (it must is reflexive, symmetric, and transitive). In addition, it must is consistent (if the objects is not modified and then it must keep returning the same value). furthermore, O.equals (null) must always return false.

Hashcode () (javadoc) must also be consistent (if the object isn't modified in terms of equals (), it must keep returning t He same value).

The relation between the methods Is:

Whenever A.equals (b), then A.hashcode () must is same as B.hashcode ().
In Practice:

If you override one and then you should override the Other.

With the same set of fields, you use the compute equals () to compute hashcode ().

Use the excellent helper classes Equalsbuilder and Hashcodebuilder from the Apache Commons Lang library. An example:

 public classperson {PrivateString name; Private intage ; // ...@Override public inthashcode () {return NewHashcodebuilder (17, 31).//randomly chosen prime numbers//if Deriving:appendsuper (super.hashcode ()).Append (name).            Append (age).    Tohashcode (); } @Override public Booleanequals (Object obj) {if(! (objinstanceofperson )) return false; if(obj = = this)            return true; Person RHS=(person) obj; return NewEqualsbuilder (). //if Deriving:appendsuper (super.equals (obj)).Append (name, rhs.name).            Append (age, rhs.age).    Isequals (); }}

Also Remember:
When using a hash-based Collection or Map such as HashSet, linkedhashset, HashMap, Hashtable, or weakhashmap, make sure th At the hashcode () of the key objects so you put to the collection never changes while the object was in the Collection. The Bulletproof-ensure-to-make your keys immutable, which have also other Benefits.

Partii:

The Commons/lang builders is great and I have a been using them for years without noticeable performance overhead (with and Without hibernate). But as Alain writes, the guava is even nicer:

Here's a sample Bean:

 public classbean{PrivateString name; Private intlength; PrivateList<bean>children;} here' s equals () and Hashcode () implemented with Commons/lang:@Override public inthashcode () {return Newhashcodebuilder (). Append (name). append (length). append (children). tohashcode (); @Override public BooleanequalsFinalObject Obj) {    if(objinstanceofBean) {        FinalBean other =(Bean) obj; return Newequalsbuilder (). Append (name, other.name). append (length, other.length). append (chi    ldren, other.children). isequals (); } Else{        return false; }}and here with Guava: @Override public inthashcode () {returnObjects.hashcode (name, length, children);} @Override public BooleanequalsFinalObject Obj) {    if(objinstanceofBean) {        FinalBean other =(Bean) obj; returnobjects.equal (name, Other.name)&& length = = Other.length//Special handling for primitives&&objects.equal (children, other.children); } Else{        return false; }}

As can see the guava version is shorter and avoids superfluous helper objects. In case of equals, it even allows for short-circuiting the evaluation if a earlier object.equal () call returns False (to Be Fair:commons/lang have an objectutils.equals (obj1, Obj2) method with identical semantics which could be used instead of Equalsbuilder to allow short-circuiting as above).

so:yes, The Commons lang builders is very preferable over manually constructed equals () and Hashcode () methods (or Those Awful Monsters Eclipse would generate for your), but the guava versions is even Better.

And a note about Hibernate:

Be careful is about using the lazy collections in your equals (), hashcode () and toString () implementations. that'll fail miserably If you don't have an open Session.

Note (about equals ()):

A) in both versions of equals () above, you might want to use one or both of these shortcuts also:

@Override
public boolean equals (final Object Obj) {
if (obj = = This) return true; Test for reference equality
if (obj = = Null) return false; Test for NULL
Continue as above
B) depending on your interpretation of the equals () contract, you might also change the line (s)

If (obj instanceof Bean) {
To

Make sure to run a null check before this
If (obj.getclass () = = GetClass ()) {
If you use the second version, you probably also want to call Super (equals ()) inside your equals () method. Opinions differ here, the topic are discussed in this question:

Right-to-incorporate superclass into a guava objects.hashcode () implementation?
(although it ' s about hashcode (), the same applies to equals ())

Note (inspired by Comment from Kayahr)

Objects.hashcode (..) (just as the underlying Arrays.hashcode (...)) Might perform badly if you had many primitive fields. In such cases, Equalsbuilder could actually be the better Solution.

How to implement equals () and Hashcode () methods in java[reproduced]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.