gpt4 book ai didi

java - 调整哈希表的大小

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:10 24 4
gpt4 key购买 nike

我正在尝试调整哈希表的大小。我发现我的逻辑是对的,但是代码全错了。我知道在哈希表中添加元素时必须考虑负载因子,如果超过负载因子,容量就会增加一倍。

示例。 尺寸 = 3,容量 = 5
负载系数 = 5 * 0.75 = 3.75
如果我们添加一个元素 Size = 4,它超出了负载因子,因此 Capacity = 10。但是,我返回原来的Capacity

/**
* size if load >.75 or < .5
*/
private void resize(int newCap)
{
//
double capacity = buckets.length * 0.75;
//System.out.println(capacity);
if (currentSize > capacity) {
int C = buckets.length * 2;
newCap = C
//System.out.println(C);
}
}

/**
* Gets the length of the array backing this HashSet
* @return the length of the array backing this HashSet
*/
public int getCap()
{
//
int capac = buckets.cap
resize(capac);
return capac;
}

最佳答案

resize 方法中的

newCap = C 不会更改 capac 的值

您应该从 resize 方法返回 newCap

/**
* size if load >.75 or < .5
*/
private int resize(int newCap)
{
//
double capacity = buckets.length * 0.75;
//System.out.println(capacity);
if (currentSize > capacity) {
int C = buckets.length * 2;
return C;
//System.out.println(C);
}
return newCap;
}

/**
* Gets the length of the array backing this HashSet
* @return the length of the array backing this HashSet
*/
public int getCap()
{
//
int capac = buckets.cap;
capac = resize(capac);
return capac;
}

在java中,总是存在传值的。查看相关讨论here

编辑:更改了正确指出的返回类型。

关于java - 调整哈希表的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20366596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com