For the same input, why is the hash value returned by the Objects.hash() method different every time?

table of Contents

background

why

Best Practices

Reference


background

A problem was discovered during the development process. The AopMethod object was saved with Set in the project for de-duplication, but it was found that even if an object with the same content is added to the set, it can be added successfully every time.

Part of the code of the AopMethod class is as follows:

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

Through debug, it is found that even if the content of the object is exactly the same, the hash value returned by the hashCode is different each time.

AopMethod{methodName='m81', parameterTypes=[int], ignoreParameterTypes=false} hash:-1850752941
AopMethod{methodName='m81', parameterTypes=[int], ignoreParameterTypes=false} hash:-526785805

The equals and hashCode methods are automatically generated by Idea IDE. It seems that the automatic generation is not reliable. . .

 

why

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

Objects.hash calls the hahCode method internally, but the parameterTypes is an array, and the array does not have a hashCode() method.

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

 

Best Practices

Don't rely on the hashCode method automatically generated by Idea IDE.

If there is an array, wrap it with Arrays.hashCode() and use it as a parameter of the Objects.hash() method.

Change hashCode to the following implementation and it will be OK!

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

 

Reference

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

Guess you like

Origin blog.csdn.net/hanhan122655904/article/details/114369481