为什么我的字符串与==工作比较?

时间:2014-04-01 21:39:18

标签: java

我在onPostExecute

中有这个
    String test = currentActivity.getClass().getSimpleName();
    if(test == "SplashScreen"){
        Log.e("OK",test);

    } else {
        Log.e("OK",test);

    }

问题是,test的值是“SplashScreen”(我们可以在日志中看到),但代码永远不会进入if,只能在else

为什么会这样?

5 个答案:

答案 0 :(得分:3)

正如其他人已经说过你不能在字符串上使用==运算符。 原因是字符串是对象而不是原始数据类型。 据说,如果我没有弄错,==运算符将检查两个字符串是否在内存中具有相同的内存点。

答案 1 :(得分:2)

使用equals比较字符串:

 if(test.equals("SplashScreen"){ 
  Log.e("OK",test);

 } else {
    Log.e("OK",test);

}

答案 2 :(得分:2)

你不能在字符串上使用==。你应该使用:

"SplashScreen".equals(test)

测试可能为null,最好在“SplashScreen”上调用equals(),因为你知道它不是null。

答案 3 :(得分:0)

请勿将字符串与==使用.equals()

进行比较
String test = currentActivity.getClass().getSimpleName();
if(test.equals("SplashScreen")){
    Log.e("OK",test);

} else {
    Log.e("OK",test);

}

答案 4 :(得分:0)

最好使用equalsIgnoreCase(String string)。

 String test = currentActivity.getClass().getSimpleName();
if(test.equalsIgnoreCase("SplashScreen")){
    Log.e("OK",test);

} else {
    Log.e("OK",test);

}