<分区>
if(foo != bar)
Log(foo + " is not equal to " + bar);
打印:
FooBar@ca4c33db is not equal to FooBar@ca4c33db
这发生在 Android 上。 FooBar 是我自己的自定义类。我在调试器中仔细检查了它。
<分区>
if(foo != bar)
Log(foo + " is not equal to " + bar);
打印:
FooBar@ca4c33db is not equal to FooBar@ca4c33db
这发生在 Android 上。 FooBar 是我自己的自定义类。我在调试器中仔细检查了它。
最佳答案
你应该使用equals()
if(!foo.equals(bar))
但是使用 String
你可以执行以下操作,因为 String
类已经实现了 equals()
方法。
String a = "hi";
String b = "hii";
if (a!=b){
System.out.println("yes");
}else {
System.out.println("no");
}
输出:
yes
如果您想按照自己的方式行事,则必须覆盖 equals()
方法。
示例:没有覆盖 equals()
public class Test {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
现在看看这个
Test a = new Test();
Test b = new Test();
a.setAge(1);
a.setName("hi");
b.setAge(1);
b.setName("hi");
if (a!=b){
System.out.println("yes");
}else {
System.out.println("no");
}
输出:
yes
现在你可以在这里看到同样的问题。
关于java - 这里的 != 运算符有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21625561/
相关文章:
java - 如何从JAVA文件中读取特定用户ID的最后一个条目
android - 如何在 Android Things 中预览 Raspberry 中的相机?
android - 带有 java.lang.reflect.InvocationTargetException 的 android 上的 JAIN SIP
java - Android Q(API 级别 29)不加载 HTTPS 网站。给出错误:(net::ERR_ACCESS_DENIED)
android - 安装错误 : INSTALL_PARSE_FAILED_MANIFEST_MALFORMED
Java:HttpClient 中的自动 cookie 处理?