Use Objects.hash() or own hashCode() implementation?

前端 未结 5 1539
清酒与你
清酒与你 2021-01-01 08:24

I have recently discovered the Objects.hash() method.

My first thought was, that this tidies up your hashCode() implementation a lot. See the following

5条回答
  •  借酒劲吻你
    2021-01-01 09:08

    Following is implementation of Objects.hash - which is calling Arrays.hashCode internally.

    public static int hash(Object... values) {
        return Arrays.hashCode(values);
    }
    

    This is implementation of Arrays.hashCode method

    public static int hashCode(Object a[]) {
        if (a == null)
            return 0;
    
        int result = 1;
    
        for (Object element : a)
            result = 31 * result + (element == null ? 0 : element.hashCode());
    
        return result;
    }
    

    So I agree with @Andy The cost of creating of these "unnecessary" objects may add up if hashCode is called frequently. If you are implementing yourself it would be faster.

提交回复
热议问题