我正在尝试调整哈希表
的大小。我发现我的逻辑是对的,但是代码全错了。我知道在哈希表中添加元素时必须考虑负载因子,如果超过负载因子,容量就会增加一倍。
示例。 尺寸 = 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/