Java 为什么';t我的字符串与==工作的比较?
在我的Java 为什么';t我的字符串与==工作的比较?,java,Java,在我的onPostExecute中有这样一个: String test = currentActivity.getClass().getSimpleName(); if(test == "SplashScreen"){ Log.e("OK",test); } else { Log.e("OK",test); } 问题是,test的值是“SplashScreen”(我们可以从日志中看到),但是代码永远不会出现在if中,而只出现在
onPostExecute
中有这样一个:
String test = currentActivity.getClass().getSimpleName();
if(test == "SplashScreen"){
Log.e("OK",test);
} else {
Log.e("OK",test);
}
问题是,test的值是“SplashScreen”(我们可以从日志中看到),但是代码永远不会出现在if
中,而只出现在else
中
为什么会发生这种情况?使用
equals
比较字符串:
if(test.equals("SplashScreen"){
Log.e("OK",test);
} else {
Log.e("OK",test);
}
不能在字符串上使用==。你应使用:
"SplashScreen".equals(test)
测试可能为null,最好在“SplashScreen”上调用equals(),因为您知道它不是null。不要将字符串与
==
进行比较,使用.equals()
最好使用equalsIgnoreCase(字符串)
正如其他人已经说过的,不能在字符串上使用==运算符。 原因是字符串是对象而不是基本数据类型。
如果我没弄错的话,==操作符将检查这两个字符串在内存中是否有相同的内存点 您是否尝试过使用
test.equals(“SplashScreen”)
?看看这里是的,当然。。。我忘了。。。。我需要停止Php:Dthx@Myste-在提问之前,您需要开始搜索答案。这个问题以前被问过几千次。
String test = currentActivity.getClass().getSimpleName();
if(test.equals("SplashScreen")){
Log.e("OK",test);
} else {
Log.e("OK",test);
}
String test = currentActivity.getClass().getSimpleName();
if(test.equalsIgnoreCase("SplashScreen")){
Log.e("OK",test);
} else {
Log.e("OK",test);
}