美文网首页
不同类型底层的hashCode方法

不同类型底层的hashCode方法

作者: 梦想旅行家Jirry | 来源:发表于2019-08-23 17:34 被阅读0次

不同类型底层的hashCode方法

Integer

public static int hashCode(int value) {
        return value;//返回的就是底层包装的基本数据类型int对应的数值value
    }

Double

public int hashCode() {
        return Double.hashCode(value);
    }
public static int hashCode(double value) {
        long bits = doubleToLongBits(value);
        return (int)(bits ^ (bits >>> 32));
    }

String

public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

自定义类Student

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

如何减少冲突?

  1. 将主数组 长度变大
  2. 优化计算位置的函数。
  3. hashCode()和equals()方法调用几次,什么时候调用?
    • hashCode每次都调用,equals只有在冲突的时候(在同一位置)上,才调用。

相关文章

网友评论

      本文标题:不同类型底层的hashCode方法

      本文链接:https://www.haomeiwen.com/subject/rowtectx.html