Why Series override equals method must override hasCode method?

Object source code and comments

Object equals method is public, then we usually rewrite the equals method in their own classes, while the method must be rewritten hasCode know why rewrite the equals method must override hasCode way to do that?

/**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
     * <p>
     * The general contract of {@code hashCode} is:
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during
     *     an execution of a Java application, the {@code hashCode} method
     *     must consistently return the same integer, provided no information
     *     used in {@code equals} comparisons on the object is modified.
     *     This integer need not remain consistent from one execution of an
     *     application to another execution of the same application.
     * <li>If two objects are equal according to the {@code equals(Object)}
     *     method, then calling the {@code hashCode} method on each of
     *     the two objects must produce the same integer result.
     * <li>It is <em>not</em> required that if two objects are unequal
     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
     *     method, then calling the {@code hashCode} method on each of the
     *     two objects must produce distinct integer results.  However, the
     *     programmer should be aware that producing distinct integer results
     *     for unequal objects may improve the performance of hash tables.
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (This is typically implemented by converting the internal
     * address of the object into an integer, but this implementation
     * technique is not required by the
     * Java™ programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */
    public native int hashCode();

    /**
     * Indicates whether some other object is "equal to" this one.
     * <p>
     * The {@code equals} method implements an equivalence relation
     * on non-null object references:
     * <ul>
     * <li>It is <i>reflexive</i>: for any non-null reference value
     *     {@code x}, {@code x.equals(x)} should return
     *     {@code true}.
     * <li>It is <i>symmetric</i>: for any non-null reference values
     *     {@code x} and {@code y}, {@code x.equals(y)}
     *     should return {@code true} if and only if
     *     {@code y.equals(x)} returns {@code true}.
     * <li>It is <i>transitive</i>: for any non-null reference values
     *     {@code x}, {@code y}, and {@code z}, if
     *     {@code x.equals(y)} returns {@code true} and
     *     {@code y.equals(z)} returns {@code true}, then
     *     {@code x.equals(z)} should return {@code true}.
     * <li>It is <i>consistent</i>: for any non-null reference values
     *     {@code x} and {@code y}, multiple invocations of
     *     {@code x.equals(y)} consistently return {@code true}
     *     or consistently return {@code false}, provided no
     *     information used in {@code equals} comparisons on the
     *     objects is modified.
     * <li>For any non-null reference value {@code x},
     *     {@code x.equals(null)} should return {@code false}.
     * </ul>
     * <p>
     * The {@code equals} method for class {@code Object} implements
     * the most discriminating possible equivalence relation on objects;
     * that is, for any non-null reference values {@code x} and
     * {@code y}, this method returns {@code true} if and only
     * if {@code x} and {@code y} refer to the same object
     * ({@code x == y} has the value {@code true}).
     * <p>
     * Note that it is generally necessary to override the {@code hashCode}
     * method whenever this method is overridden, so as to maintain the
     * general contract for the {@code hashCode} method, which states
     * that equal objects must have equal hash codes.
     *
     * @param   obj   the reference object with which to compare.
     * @return  {@code true} if this object is the same as the obj
     *          argument; {@code false} otherwise.
     * @see     #hashCode()
     * @see     java.util.HashMap
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

The above is the Object object equals hasCode and signature methods and instructions.

Why override equals method

Determining whether the current object is equal to a number of objects, to achieve equivalence relation on non-null object map. this == obj, can be seen, this is a reference to the equivalence determination target returns true only if obj and this is a point to use the application. This is the only examples of the determination, we usually use equals, in fact, the only instance judgment did not want to, but you want a few more inside (custom) property values ​​are equal, to determine whether the same "stuff."

Contract:
Reflexive (reflexivity): x is non-null, x.equals (x), must return to true.
Symmetric (symmetry): x, y are not null, and if x.equals (y) returns true, then y.equals (X).
transitive (transitive): x, y, z are not null, and if x.equals (y) returns true, y.equals (z), then x.equals (z) returns true .
consistent (consistency): for any non-null x \ y, in the absence of information on the premise modify these objects under multiple calls, x.equals (y) the result is the same.
Non-null x, x.equals (null) return false.

Here is the Book class equals rewrite realized by bookN, bookName determine whether the same book (thing), instead of the two objects to determine whether the reference is the same.

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return  Objects.equal(bookNo, book.bookNo) &&
                Objects.equal(bookName, book.bookName);
    }

Why rewrite hasCode method

hasCode Wedge about:
1. In the absence of any time modify an object's premise, multiple calls hasCode method of the same object, the return value must be the same Integer value.
2. If two objects equals the result is true, then hasCode value must be the same.
3. If two objects equals to false, then hasCode not necessarily different.

If the override equals methods do not override hasCode method, then the second wedge about violation bound. So every time hasCode must follow equals rewrite and rewrite.

Expand knowledge

Is not someone is to ask: If you do not rewrite hasCode, can not I? It is contrary to carve about not it? Only equals rewrite Is there a problem?
HasCode will come out of this scenario in the collection.

Java in the collection (Collection) There are two types, one is List, then there is a class Set. Elements within the former set is ordered, the element can be repeated; disorder latter element, but the element can not be repeated. So here there is a more serious problem: in order to ensure non-repetition of elements, whether two elements should repeat what basis to judge it? This is the method of Object.equals. However, if each additional element to check once, when a lot of elements, added to the number of elements in a set of relatively very much. That is, if the collection now has 1000 elements, then the first 1001 elements to the collection, it is necessary to call the equals method 1000. This obviously will greatly reduce efficiency.

So, Java uses the principle of the hash table. Hash algorithms are also known as hashing algorithm, is the data directly to a designated address in accordance with a specific algorithm. It is appreciated that this simple, hashCode method is actually returns the image object storage location.

When you add elements in a collection, first call hasCode method, if the position is not an element, then directly stored here, if there are elements, so then call the equals method compared with new elements, if the same does not exist, if not the same as the description collision (conflict), collision resolution methods varied, will eventually be stored in a suitable location. Once you have hasCode, the number of calls equals greatly reduced, usually once or twice to get.

Extended content may be interested in their own in-depth study. Why series uses short, easy to understand manner summarized some of the problems in the work, often appearing in the interview to answer. If there is an error, please contact me in a timely manner, so as not to mislead others.

Guess you like

Origin blog.51cto.com/4837471/2447956