0

Sorry if I ask a stupid question, long time no practice with Java...... I wrote some code to simulate the Hash Table. Here is one function of my code:

protected int find(K key){
    int avail=-1;
    int i=hashValue(key);
    int j=i;
    do{
        Entry<K, V> element = bucket[i];

        if(element==null){
            if(avail<0){
                avail=i;
            }
            break;
        }

        if(key.equals(element.getK())){
            return i; // found
        }

        if(element==this.used){
            if(avail<0){
                avail=i;
            }
        }
        i=(i+1)%capa;
    }while(i!=j);
    return -(avail+1); // return a hash address
}

The strange thing is, when I change the if statement if(element==null) back a little bit (anywhere but the very beginning of the structure), it will then warn me it is a dead code:

protected int find(K key){
    int avail=-1;
    int i=hashValue(key);
    int j=i;
    do{
        Entry<K, V> element = bucket[i];

        if(key.equals(element.getK())){
            return i; // found
        }

        if(element==this.used){
            if(avail<0){
                avail=i;
            }
        }

        // dead code then
        if(element==null){
            if(avail<0){
                avail=i;
            }
            break;
        }
        //dead code then

        i=(i+1)%capa;
    }while(i!=j);
    return -(avail+1); // return a hash address
}

Anyone knows which part goes wrong?

Prince Luo
  • 101
  • 1
  • 8

1 Answers1

8

In your second code example, element can't possibly be null since you have already referenced it in the lines above: element.getK() in line

if(key.equals(element.getK()))

If it was null at that point, then you would have gotten a NullPointerException that you didn't catch. And that means that the method would not have continued to your if(element == null) statement.

If element is not null, then the body of your if statement won't be executed either.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
  • Thanks a million. That should be the case. I should go and test with some data first, which the alarm will raise and I will know...... – Prince Luo Feb 08 '17 at 03:57