1

I am trying to re-size a hash table. I find that my logic is correct, but the code is all wrong. I know that when adding elements into a hash table you must consider the load factor, if the load factor is exceeded, the capacity doubles.

Example. Size = 3, Capacity = 5.
Load Factor = 5 * 0.75 = 3.75
If we add an element Size = 4, which exceeds the load factor, thus Capacity = 10. However, I am return the original 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;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3011391
  • 67
  • 2
  • 8

1 Answers1

0

newCap = C in method resize will not change the value of capac

You should be returning the newCap from resize method

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

In java, there is always pass-by-value. See a relevant discussion here

Edit: Changed the return type as rightly pointed out.

Community
  • 1
  • 1
hari
  • 491
  • 5
  • 6