【问题标题】:If statement using == gives unexpected result [duplicate]如果使用 == 的语句给出了意外的结果 [重复]
【发布时间】:2012-04-09 21:20:31
【问题描述】:
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);
        }
    }
}

我有一个名为“words”的列表,它包含字符串。这里 Log.i 适用于“word”标签,但“step”语句不执行。似乎 If 条件不能很好地工作。尽管“单词”列表包含类似的字符串,但这种方法永远不会进入它。会有什么问题。请帮忙..

【问题讨论】:

标签: java methods


【解决方案1】:

您需要使用String.equals(),而不是==== 检查两个 Object 引用是否指向同一个 Object

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

来自 Java 语言规范 3.015.21.3 参考相等运算符 == 和 != 部分:

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

【讨论】:

  • 想不通..我脑子里想了很多!!谢谢。
  • 这确实像宣传的那样有效,尽管我更喜欢切换两者。 "s".equals(word) 没有投掷 NullPointerException 的风险。
  • @DennisLaumen,同意。更新了答案。
  • - 1 代表修订版答案中的“尤达条件”
  • @baba,如果wordnull,则'yodo 条件'(以前从未听说过)可以防止NullPointerException。我更喜欢这种风格,并且错误地没有在我的原始答案中使用它。为什么是-1?答案是正确的。
【解决方案2】:

在java中你需要比较字符串和equals:

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

【讨论】:

    【解决方案3】:

    正如其他人所说,您使用object.equals(otherObject) 来比较Java 中的对象。

    但是你的方法是完全错误的。

    试试吧

    Set stopWords = new HashSet(Arrays.asList("s", "t", "am",
                                              "is", "are", "was", "were",
                                              "has", "have", "been",
                                              "will", "be", ...));
    

    然后

    private void refineWords() {
        words.removeAll(stopWords);
    }
    

    你应该完成了。


    此外,请注意,使用您当前的代码,您将获得 ConcurrentModificationException,因为您尝试在迭代时更改集合。

    所以如果你不能使用上面的words.removeAll(stopWords),那么你必须改用更详细的Iterator.remove()方法:

    private void refineWords() {
        for (Iterator<String> wordsIterator = words.iterator(); wordsIterator.hasNext(); ) {
            String word = wordsIterator.next();
            if (stopWords.contains(word)) {
                wordsIterator.remove();
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      您可能希望使用equalsIgnoreCase(..) 方法进行更精细的优化。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-06
        • 2015-02-07
        • 1970-01-01
        • 2012-11-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多