有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java hashMap的哈希如何保证不超过8次冲突?

我在问专家,所以不需要简单的答案。 在描述HashMaphash方法时说:

This function ensures that hashCodes that differ only by constant multiples at each bit position have a bounded number of collisions (approximately 8 at default load factor).

但他们是怎么做到的?该方法显示确定性行为——如果将相同的hashCode作为参数传递,则得到相同的结果。因此,如果你将超过8个对象作为地图的关键点传递(如果你没有重叠负载系数),它们将被放在同一个桶中。那么,这种方法如何保证有限的碰撞次数呢

为了测试我是否正确,我使用了这个。假设我们想要一张32大小的地图,负载系数为0.75。你可以把23个物体放进地图,它不会调整大小

Map testMap = new HashMap<SimpleHashCodeObject, String>(32);

然后定义一些对象:

public class SimpleHashCodeObject {
    private String name;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        SimpleHashCodeObject that = (SimpleHashCodeObject) o;
    return false;
    }

    @Override
    public int hashCode() {
        if(name.equals("a")) return 1;
        if (name.equals("b"))  return 2;
        else return 3;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

最后,你填充了一切:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Map testMap = new HashMap<SimpleHashCodeObject, String>(32);


    for(int i = 1; i <= 12; i++){
        SimpleHashCodeObject sho = new SimpleHashCodeObject();
        sho.setName("a");
        testMap.put(sho, new Integer(i).toString());
    }

    for(int i = 13; i <= 23; i++){
        SimpleHashCodeObject sho2 = new SimpleHashCodeObject();
        sho2.setName("b");
        testMap.put(sho2, new Integer(i).toString());
    }
}

在调试窗口中,我可以在这个映射中看到两个bucket,每个bucket包含8个以上的元素

enter image description here

为什么会这样?你能澄清一下情况吗


共 (0) 个答案