1

I can't figure out what's wrong with my code but it fails at deletion of PS in the following [null, null, null, PS]

 /**
 * Removes the specified string from this hash table     
 * (if the string is in this table).    
 */
public void delete(String s) {
    // TODO
    int k = 0;
    for (int i=0;i<M;i++) {
        if (keys[i] != null) {
            if (keys[i] == s) {

                k = i;
        }
        }
    }
    keys[k] = null;
    for (int i=k;i<M;i++) {
        if (keys[i+1]!=null) {
            keys[i] = keys[i+1];
        }
    }
    N--;


    // halves size of array if it's 12.5% full or less
    if (N > 0 && N <= M/8) resize(M/2);
}
Jess
  • 19
  • 2

1 Answers1

2

You didn't specify what the error is but looking at the code I see these problems:

  1. Comparison between String should be performed using equals and not == otherwise you are not comparing the values of the strings but their references
  2. if keys size is M then keys[i+1] will cause an out of bounds exception in the last cycle of the second for loop
Loris Securo
  • 7,538
  • 2
  • 17
  • 28