gpt4 book ai didi

java - 为什么 != 和 == 的行为不像 Java 中的 equals 方法?

转载 作者:行者123 更新时间:2023-12-02 00:38:25 25 4
gpt4 key购买 nike

Possible Duplicates:
Java String.equals versus ==
whats the difference between ".equals and =="

public String getName() {
return new String("foobar");
}

if(getName() != "foobar2") {
//Never gets executed, it should, wtf!.
}

if(!getName().equals("foobar2")) {
//This works how it should.
}

所以是的,我的问题很简单..为什么不 !=行为与 !equals() 相同又名 ( not Equals )。

我看不出任何失败的逻辑原因,在我看来,两者都是完全相同的代码,WTH。

查看 java 运算符 http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

你可以清楚地看到平等== !=

是相等运算符,当然我通常使用 !=只在数字上..但我的思绪开始徘徊,为什么它不适用于 String

编辑:这是看起来更像实际问题的东西..

    for (ClassGen cg : client.getClasses().values()) {
final ConstantPoolGen cp = cg.getConstantPool();
if(cp.lookupInteger(0x11223344) != -1) {
for (Method m : cg.getMethods()) {
System.out.println("lots of class spam");
if(m.getName() != "<init>") continue;
System.out.println("NEVER GETS HERE, 100% SURE IT HAS CONSTRUCTOR LOL");
}
}
}

最佳答案

使用 != 意味着您检查内存中的实例引用,并且相同的实例将在该比较中为您提供 true

当您执行 new String("foobar") 时,会在内存中创建一个新的“foobar”,并且使用 == 进行比较将返回 false。

调用intern()该新字符串可能会改变此行为,因为该字符串现在将被抓取或添加到字符串池中。

无论如何,使用“equals()”更安全。

关于java - 为什么 != 和 == 的行为不像 Java 中的 equals 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7072135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com