1

i'm supposed to implement my own hash table through linear probing, however i'm having trouble with the remove function. it doesn't work correctly but i can't pinpoint the problem:

public void remove(Student s){

    if(s==null) throw new NullPointerException("Student is null");  /*check if student is null*/

    if (!contains(s)){                                               /*stop if students is not in table*/
        throw new NullPointerException();
    }

    int i = hashFunction(s);
    for(int j = 0; j<array.length; j++){
        if(s.equals(array[j])){                                              /*found student*/
            array[j]=null;                                                  /*delete student*/
            break;
        }
    }

    for(int k= i; k<array.length; k++){             /* find out if next element exists, if yes, move it to the gap of deleted student */
        if(!(array[k]==null)){
        int tempnext= hashFunction(array[k]);

            if(i <= tempnext){
                array[i]=array[tempnext];
            }
        }
    }   
}

my debugger shows this as an output, so clearly my method has problems with gaps in the table:

Start:

Array-Indices: [ 0] [ 1] [ 2] [ 3] [ 4] [ 5] [ 6] [ 7]
Hash-Values:   [ 6] [ 1] [__] [ 6] [ 0] [ 5] [ 3] [ 0]
Number:        [ 9] [ 6] [__] [ 2] [ 3] [ 4] [ 5] [ 8]

Removing s6

Array-Indices: [ 0] [ 1] [ 2] [ 3] [ 4] [ 5] [ 6] [ 7]
Hash-Values:   [ 6] [ 6] [__] [ 6] [ 0] [ 5] [ 3] [ 0]
Number:        [ 9] [ 2] [__] [ 2] [ 3] [ 4] [ 5] [ 8]

Removing s5

Array-Indices: [ 0] [ 1] [ 2] [ 3] [ 4] [ 5] [ 6] [ 7]
Hash-Values:   [ 6] [ 6] [__] [ 5] [ 0] [ 5] [__] [ 0]
Number:        [ 9] [ 2] [__] [ 4] [ 3] [ 4] [__] [ 8]

thanks in advance for any help!

Meowzen
  • 113
  • 1
  • 3
  • 15
  • 1
    Side note on code quality: your names could be improved: names should tell the reader what the thing behind **is**; not how it is implemented. Meaning: *array* doesn't tell you anything about its content. Renaming it to *studentsKnownToHashSet" or something alike ... would make it very clear to the user what to expect in that array. Besides: you do not want to make the "type of collection" part of the name of the variable ... it is an array today, maybe a List tomorrow, and a Set the day after. hashFunction() is also not a good name, something like computeHashFor() would be more telling. – GhostCat Jun 01 '16 at 16:51
  • Then: throwing a NullPointerException for unknown Students is very misleading. Compare that to `throw new IllegalArgumentException("Unable to remove unknown student: " + student + " from set");` – GhostCat Jun 01 '16 at 16:54
  • the exceptions i had to throw were already given by my school. hashFunction was already implemented by them, too. but in general you're right, yes. thank you. – Meowzen Jun 01 '16 at 17:02
  • Tell your school that their input is sub-standard ;-) – GhostCat Jun 02 '16 at 09:10

0 Answers0