如果使用==的语句给出了意外的结果 [英] If statement using == gives unexpected result

查看:107
本文介绍了如果使用==的语句给出了意外的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void refineWords() {
    for(String word : words){
        Log.i("word", word);
        if (word == "s" || word == "t" || word == "am" || word == "is" || word == "are" || word == "was" || word == "were" || word == "has" || 
            word == "have" || word == "been" || word == "will" || word == "be" || word == "would" || word == "should" || word == "shall" || 
            word == "must" || word == "can" || word == "could" || word == "the" || word == "as" || word == "it" || word == "they" ||
            word == "their" || word == "he" || word == "she" || word == "his" || word == "her" || word == "him" || word == "its" ||
            word == "in" || word == "on" || word == "a" || word == "at") {

            Log.i("step", "step Success!!");
            words.remove(word);
        }
    }
}

我有一个名为单词,它包含字符串。这里Log.i适用于word标签,但step语句不会执行。似乎If条件不能正常工作。虽然单词列表包含类似的字符串,但是这种方法永远不会进入它。会出现什么问题。请求帮助..

I have a List called "words" and it contains strings. Here the Log.i works for the "word" tag fine but the "step" Statement does not executes. Seems the If condition does not work well. like this method never goes into it although the "words" list contains similar strings. What would be the problem. pleas help..

推荐答案

您需要使用 String.equals(),而不是 == == 检查两个 Object 引用是否引用相同的对象

You need to use String.equals(), not ==. == checks if two Object references refer to the same Object:

if("s".equals(word) || "t".equals(word) || ...

来自 15.21.3部分参考等式运算符==和!= Java语言规范3.0


虽然==可用于比较String类型的引用,例如一个等式
测试确定两个操作数是否引用相同的String
对象。如果操作数是不同的String对象,则结果为false,即使
它们包含相同的字符序列可以通过方法调用s.equals(t)测试两个字符串s和t
的内容是否相等。

While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters. The contents of two strings s and t can be tested for equality by the method invocation s.equals(t).

这篇关于如果使用==的语句给出了意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆