Java 为什么我的字符串到字符串比较失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3576413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:02:40  来源:igfitidea点击:

Why is my String to String comparison failing?

javaandroidstring

提问by Chuck Hriczko

I have an Android app where I want to check to see if an app name that is installed matches a string passed to the function containing this code. The code and example is below:

我有一个 Android 应用程序,我想在其中检查已安装的应用程序名称是否与传递给包含此代码的函数的字符串匹配。代码和示例如下:

private Boolean checkInstalledApp(String appName){
    PackageManager pm = this.getPackageManager(); 
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); 
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); 
    List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);
    Boolean isInstalled = false;
    for(ResolveInfo info: list) {
      if (info.activityInfo.applicationInfo.loadLabel( pm ).toString()==appName){
          isInstalled = true;
          break;  
      }
    } 

    return isInstalled;
}

Assuming you called checkInstalledApp("SetCPU");and the app name on the phone is called the same thing it should return true. However, it never does. I logged the results and it should match up but it does not. Can anyone please enlighten me as to why this doesn't work?

假设您checkInstalledApp("SetCPU");拨打电话并且手机上的应用程序名称与它应该返回的名称相同true。然而,它从来没有。我记录了结果,它应该匹配,但它不匹配。任何人都可以请教我为什么这不起作用?

采纳答案by Eton B.

Use the String's equals() method instead of the == operator for comparing strings:

使用 String 的 equals() 方法而不是 == 运算符来比较字符串:

info.activityInfo.applicationInfo.loadLabel( pm ).toString().equals(appName)

In Java, one of the most common mistakes newcomers meet is using ==to compare Strings. You have to remember, ==compares the object references, not the content.

在 Java 中,新手遇到的最常见错误之一是使用==比较字符串。您必须记住,==比较的是对象引用,而不是内容。

回答by Blundell

回答by Bouchehboun Saad

public static boolean compaireString (String string, String string2) 
{
    // string == null && String2 == null or they reference the same object
    if (string == string2) return true;
    //we have to be sure that string is not null before calling a methode on it
    if (string != null && string.equals(string2)) return true;

   return false;
}