There are three methods in the object class in Java that have hashcode (), Equals (), and toString (), so there are three methods in all the classes in Java.
In the object class the implementation of the ToString () method is the address of the printed object, which is printed out of the human can not understand, this information is not useful to print out. So in the effective Java book, the authors recommend that we try to rewrite this method so that it prints out useful information. Implementing the ToString () method is a cumbersome task for the machine, so we should help by using a mature class library. The well-known class library guava in the Java camp can help us do the job. The following is a code example:
@Override public String toString () { return Moreobjects.tostringhelper (this) . Add ("Housenumber", Housenumber) . Add(" Street, Street) . toString (); }
If we design the class to work with HashMap, HashSet, the hash is worth the action. Then you need to rewrite the hashcode (), Equals () method, and the two methods must be rewritten together, and if you write only one of them there will be a hard-to-describe error. And the two methods are consistent. Before java7 this work is still difficult, because generating efficient hash values is a difficult task. So it is best to implement these two methods before java7, preferably with a mature class library, such as guava. But after Java7, Java adds the two tool methods in guava to the standard class library, so we can use them directly. The following is a code example:
@Override public boolean equals (Object obj) { if (obj = = null) return false; if (obj = = this) return true; if (! ( obj instanceof Address)) return false; Final Address other = (Address) obj; Return objects.equal (This.housenumber, Other.housenumber) && objects.equal (This.street, Other.street) && objects.equal (this.city, other.city) && objects.equal (this.stateorprovince, other.stateorprovince) && objects.equal (This.country, other.country); } @Override public int hashcode () { return Objects.hashcode ( this.housenumber, This.street, This.city, This.stateorprovince, this.country); }
Java class hashcode (), Equals (), toString () method