发布于 4年前

Java Objects.hash()与自己实现的hashCode()比较

Java 7新增了Objects类,它为对象提供了一些便捷的静态方法,如equals(),hashCode(),hash(),compare(),toString()等等。

这里比较一下Objects.hash()与自己实现的hashCode()。

传统实现的hashCode

@Override
public int hashCode() {
    int hash = 5;
    hash = 67 * hash + (int)(this.id ^ (this.id >>> 32));
    hash = 67 * hash + (int)(this.timestamp ^ (this.timestamp >>> 32));
    hash = 67 * hash + Objects.hashCode(this.severity);
    hash = 67 * hash + Objects.hashCode(this.thread);
    hash = 67 * hash + Objects.hashCode(this.classPath);
    hash = 67 * hash + Objects.hashCode(this.message);
    return hash;
}

使用Objects.hash()

@Override
public int hashCode() {
    return Objects.hash(id, timestamp, severity, thread, classPath, message);
}

Objects.hash()内部实现实则为Arrays.hashCode()方法

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

Arrays.hashCode()源码

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

注意Objects.hash(Object...),它的参数为不定参数,需要为Object对象。这会有以下一些影响:

  1. 对基本类型做hashCode需要转换为包装类型,如long转换为Long
  2. 会创建一个Object[]数组

如果hashCode()方法被频繁调用的话,会有一定的性能影响。

©2020 edoou.com   京ICP备16001874号-3