微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么如果比较在java中不起作用

我在 java中创建一个哈希表.
搜索功能中,我在IF语句中进行了一些比较.但它没有做任何比较.

这是我的代码的一部分.

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

即使表[pos]和键是相同的,它也不起作用!
但我将非常简单的赋值变量添加到另一个变量.这行得通!我不知道为什么会这样.我想知道它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;
}

解决方法

好吧,如果table [pos]和key都是Integer(并且table [pos]必须是引用类型,因为你在while语句中将它与null进行比较),它们应该与equals进行比较,而不是与==进行比较,因为两个不同的Integer对象可能具有相同的int值.

将table [pos]分配给int变量x时,它将取消框为原始值.

现在,当您将int x与Integer键进行比较时,该键也将取消装入int,并且int比较适用于==.

这可以通过以下简短示例来证明:

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

哪个输出

false
true

代码如下:

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+".");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐