なぜシリーズオーバーライドメソッドがhasCodeメソッドをオーバーライドする必要があります等しいですか?

オブジェクトのソースコードとコメント

オブジェクトは、メソッドが、なぜそれをするhasCodeの方法をオーバーライドする必要がありequalsメソッドを書き換える知っhasCodeを書き直さなければならないが、我々は通常、自分のクラスでequalsメソッドを書き換える方法が公開されて等しいですか?

/**
     * 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);
    }

上記目的オブジェクトがhasCodeおよび署名方法及び命令に等しくなります。

なぜオーバーライドメソッドに等しいです

現在のオブジェクトが非ヌルオブジェクトマップ上の同値関係を達成するために、オブジェクトの数に等しいか否かを決定します。この== OBJ、これは同値判定対象のみOBJ場合にtrueを返し、これがアプリケーションを使用する点で参照され、見ることができる。これは決定の単なる例であり、我々が通常使用することは、実際に、等しいです唯一のインスタンス判断はしたくなかったが、あなたは内部のいくつかのより多くを望ん(カスタム)プロパティ値が同じかどうかを判断するために、同じである「もの」。

契約:
再帰(反射性):xが非ヌルであるについて、x.equals(x)は、trueに戻らなければならない。
対称(対称)で、x、yはヌルではなく、x.equals(y)がtrueを返す場合。次いでy.equals(X)
推移(推移):X、Y、Zはヌルではなく、x.equals(y)がtrueを返す場合、y.equals(Z)、次いで、x.equals(z)がtrueを返します。
一貫性(整合性):任意の非ヌルのX \ yに対する、前提の情報が存在しない状態で複数の呼び出しの下でこれらのオブジェクトを変更について、x.equals(y)の結果は同じです。
null以外のxについて、x.equals(ヌル)がfalseを返します。

ここBookクラスがbookNによって実現書換等しいです、bookNameではなく、二つのオブジェクトの同じ本(もの)は、参照が同じであるかどうかを判断するかどうかを判断します。

@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);
    }

なぜhasCodeメソッドを書き換えます

hasCodeウェッジについて:
1.任意の時間が存在しない場合には、オブジェクトの前提を変更し、複数の呼び出しに同じオブジェクトのhasCodeメソッドは、戻り値は同じ整数値でなければなりません。
2. 2もしオブジェクトが結果が真である等しく、そしてhasCode値が同じでなければなりません。
3. 2の場合のオブジェクトはhasCode必ずしも異なっていない、その後、falseに等しいです。

オーバーライドメソッドはhasCodeメソッドをオーバーライドしないと等しい場合は、違反についての第二のくさびが結合しました。だから、毎回のhasCodeは書き換えと書き換え対等に従わなければなりません。

知識を展開

私は、あなたがhasCodeを書き換えていない場合はすることはできません:いない誰かが尋ねることですか?それではないについて彫るに反しているのですか?唯一の問題はありリライト等しいですか?
HasCodeは、コレクション内の、このシナリオから出てくるだろう。

コレクション(コレクション)でのJavaの2種類があり、1はリストで、そのクラスのセットがあります。前者のセット内の要素は、順序付けされた要素を繰り返すことができ、障害後者の要素が、要素を繰り返すことができません。要素の非繰り返しを確実にするために2つの要素がそれを判断するためにどのような根拠を繰り返す必要があるかどうか、:だからここより深刻な問題があるのでしょうか?これは、はObject.equalsの方法です。しかし、要素の多くは、比較的非常に多くのセット内の要素の数に添加した場合に追加の各要素は、一度チェックする場合。これは、コレクションが今コレクションの最初の要素1001、1000個の要素を持っている場合、equalsメソッド1000年を呼び出す必要がある、です。これは明らかに、効率を大幅に軽減します。

だから、Javaはハッシュテーブルの原理を使用しています。ハッシュアルゴリズムはまた、ハッシュアルゴリズムとして知られており、特定のアルゴリズムに応じて、指定されたアドレスにデータを直接です。なお、この単純な、hashCodeメソッドは、実際に画像オブジェクト格納場所を返すことが理解されます。

あなたは、最初の呼び出しのhasCode方法をコレクション内の要素を追加すると位置が要素でない場合、直接ここに保存された要素がある場合、その後、その同じが存在しない場合は、新しい要素と比較してequalsメソッドを呼び出し、そうでない場合の説明と同じコリジョン(衝突)、衝突解決方法を変える、最終的に適切な位置に格納されます。あなたはhasCodeを持っていたら、コール数が大幅に取得するには、通常は一度か二度、減少等しいです。

拡張コンテンツは、自分で綿密な研究に興味があるかもしれません。シリーズは短い使用なぜ、分かりやすい方法は、多くの場合、答えるためにインタビューに登場する、作業中の問題のいくつかをまとめました。エラーがある場合は他人を欺くしないように、タイムリーにご連絡ください。

おすすめ

転載: blog.51cto.com/4837471/2447956