繁体   English   中英

调整哈希表的大小

[英]Re-sizing a Hash Table

我正在尝试调整hash table的大小。 我发现我的逻辑是正确的,但是代码都是错误的。 我知道在将元素添加到哈希表中时,必须考虑load factor ,如果超出了load factor ,容量将增加一倍。

例。 Size = 3, Capacity = 5
Load Factor = 5 * 0.75 = 3.75
如果我们添加一个元素Size = 4 ,该元素超出了load factor ,那么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;
}

newCap = C在方法resize时不会更改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中,总会有值传递。 在此处查看相关讨论

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM