同じ入力に対して、Objects.hash()メソッドによって返されるハッシュ値が毎回異なるのはなぜですか?

目次

バックグラウンド

なぜ

ベストプラクティス

参照


バックグラウンド

開発プロセス中に問題が発見されました。AopMethodオブジェクトは重複排除のためにプロジェクトにSetとともに保存されましたが、同じコンテンツのオブジェクトがセットに追加されても、毎回正常に追加できることがわかりました。 。

AopMethodクラスのコードの一部は次のとおりです。

public class AopMethod {
    private String methodName;
    private Class<?>[] parameterTypes = new Class<?>[]{};
    //是否需要忽略掉参数匹配
    private boolean ignoreParameterTypes;
​
    public AopMethod() {
    }
​
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        AopMethod aopMethod = (AopMethod) o;
        return ignoreParameterTypes == aopMethod.ignoreParameterTypes &&
                Objects.equals(methodName, aopMethod.methodName) &&
                Arrays.equals(parameterTypes, aopMethod.parameterTypes);
    }
​
    @Override
    public int hashCode() {
        return Objects.hash(methodName, parameterTypes, ignoreParameterTypes);
    }
}

デバッグにより、オブジェクトの内容がまったく同じであっても、hashCodeによって返されるハッシュ値は毎回異なることがわかります。

AopMethod {methodName = 'm81'、parameterTypes = [int]、ignoreParameterTypes = false}ハッシュ:-1850752941
AopMethod {methodName = 'm81'、parameterTypes = [int]、ignoreParameterTypes = false}ハッシュ:-526785805

equalsメソッドとhashCodeメソッドはIdeaIDEによって自動的に生成されます。自動生成は信頼できないようです。

 

なぜ

Class <?> [] parameterTypes = new Class <?> [] {};

Objects.hashは内部でhahCodeメソッドを呼び出しますが、parameterTypesは配列であり、配列にはhashCode()メソッドがありません。

参照:https//stackoverflow.com/questions/29955291/why-objects-hash-returns-different-values-for-the-same-input

 

ベストプラクティス

IdeaIDEによって自動的に生成されたhashCodeメソッドに依存しないでください。

配列がある場合は、その配列をArrays.hashCode()でラップしてから、Objects.hash()メソッドのパラメーターとして使用します。

hashCodeを次の実装に変更すればOKです!

    @Override
    public int hashCode() {
        return Objects.hash(methodName, Arrays.hashCode(parameterTypes), ignoreParameterTypes);
    }

 

参照

https://stackoverflow.com/questions/29955291/why-objects-hash-returns-different-values-for-the-same-input

おすすめ

転載: blog.csdn.net/hanhan122655904/article/details/114369481