Why if comparison doesn’t work in Java

I create a hash table in Java

This is part of my code

while (table[pos]!=null) {
        if (table[pos]==key) {
            System.out.println("SEARCH "+key+" at INDEX "+home);
            return;
        }
        else {pos=h(home+p(i));
        i++;
        }
    }
    System.out.println("Failed to find "+key+".");
    return;
}

Even if the table [POS] and key are the same, it doesn't work! But I add a very simple assignment variable to another variable It works! I don't know why I want to know it XD

while (table[pos]!=null) {
        int x = table[pos];
        if (x==key) {
            System.out.println("SEARCH "+key+" at INDEX "+home);
            return;
        }
        else {pos=h(home+p(i));
        i++;
        }
    }
    System.out.println("Failed to find "+key+".");
    return;
}

Solution

Well, if both table [POS] and key are integers (and table [POS] must be of reference type, because you compare it with null in the while statement), they should be compared with equals, not = = because two different integer objects may have the same int value

When table [POS] is assigned to the int variable x, it cancels the box to the original value

Now, when you compare int x with the integer key, the key will also unload int, and the int comparison applies to = =

This can be demonstrated by the following short examples:

Integer i1 = 300;
Integer i2 = 300;
System.out.println (i1 == i2);
int i3 = i1;
System.out.println (i3 == i2);

Which output:

false
true

The code is as follows:

while (table[pos] != null) {
    if (table[pos].equals(key)) {
        System.out.println("SEARCH "+key+" at INDEX "+home);
        return;
    } else {
        pos = h(home + p(i));
        i++;
    }
}
System.out.println("Failed to find "+key+".");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>