字符串比较是使用==和equals方法的常见场景由于java.lang.String类重写了equals方法,如果两个String对象包含相同的内容,它将返回true,但==只有当两个引用指向同一对象时才会返回true。
我目前正在尝试测试(使用if语句)当前Locale变量的值。
但是返回的结果(通过在Debug模式中进行检查)为false。
这是我正在使用的代码:
Locale frLocale = new Locale("fr");
Locale usLocale = new Locale("en");
Locale currentLocale = Locale.getDefault();
Toast.makeText(this, frLocale.toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, usLocale.toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, currentLocale.getLanguage().toString(), Toast.LENGTH_SHORT).show();
if (currentLocale.getLanguage().toString() == "fr") {
currentLocale.setDefault(usLocale);
Toast.makeText(this, "Toto", Toast.LENGTH_SHORT).show();
Toast.makeText(this, currentLocale.getLanguage().toString(), Toast.LENGTH_SHORT).show();
}
Toast可以帮助我检查(没有调试模式)返回的值是什么。
我很惊讶,因为:
- 我的if的
currentLocale.getLanguage().toString()
返回"fr"
你觉得我的做事方式有什么问题吗?
如果要比较非基元数据类型,请使用equals
方法进行比较。
尝试以下解决方案:
private static final LOCATE_TEXT="fr";
Locale frLocale = new Locale(LOCATE_TEXT);
Locale usLocale = new Locale("en");
Locale currentLocale = Locale.getDefault();
Toast.makeText(this, frLocale.toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, usLocale.toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, currentLocale.getLanguage().toString(), Toast.LENGTH_SHORT).show();
if(currentLocale.getLanguage().toString().equals(LOCATE_TEXT)){
currentLocale.setDefault(usLocale);
Toast.makeText(this, "Toto", Toast.LENGTH_SHORT).show();
Toast.makeText(this, currentLocale.getLanguage().toString(), Toast.LENGTH_SHORT).show();
}