【问题标题】:Java contains doesn't work as expected because "someString" != "someString"Java contains 无法按预期工作,因为 "someString" != "someString"
【发布时间】:2012-09-15 03:30:53
【问题描述】:

我想检查字符串值 val 是否包含在字符串列表中,我们将其称为 stringList。

我正在这样做

if(stringList.contains(val)){
  System.out.println("The value is in there");
}
else{
  System.out.println("There's no such value here");
}

但似乎总是不包括该值。这是因为具有相同字符的两个字符串值实际上并不相等吗?对于“自制”类,我可以实现 hashCode() 和 equals() 并解决这个问题,我可以为 String 数据做什么?

编辑:

这里概述了我获得 val 的方式:

List<String> stringList = new ArrayList<String>();
    stringList.add("PDT");
stringList.add("LDT");
stringList.add("ELNE");

String myFile = "/folder/myFile";
InputStream input = new FileInputStream(myFile);
CSVReader reader = new CSVReader(new InputStreamReader(input), ',','"', 1);
String[] nextLine;
try {
    while ((nextLine = reader.readNext()) != null) {
    if (nextLine != null) {
        if (nextLine[6] != null){
          String val = nextLine[6];
            if(stringList.contains(val)){
            System.out.println("Success");
            }
        }
    }
}

【问题讨论】:

  • 你从哪里得到这个val?可能是编码问题
  • 除了 Binyamins 的问题:stringList 是什么运行时类型?
  • 它取自 .csv 文件,因此您可能是正确的。有什么我可以做的 - 我可以强制两者的编码相同吗?
  • 您能否向包含val 的构造/声明/类型的代码片段显示一些上下文?
  • 是的,我会这样做,我还想说...我使用了 val.equals(aValThatIsInStringList) ...也就是说,我使用了 equals 与单个项目进行比较在 stringList ...我想如果它与编码相关,这将不起作用(但我不确定)

标签: java string list equals contains


【解决方案1】:

ArrayList.contains() 使用Object.equals() 来检查是否相等(hashCode() 不涉及List)。这适用于字符串。可能,您的字符串确实不包含在列表中...

您可能忽略了一些空格或大写/小写或编码差异...

【讨论】:

  • 特殊字符似乎有问题,例如 contains 适用于 mySet.contains("familia"),但不适用于 mySet.contains("família")。该列表(在我的例子中,我使用了Set)包含这两个元素。
【解决方案2】:

请提供更多代码!

这行得通:

import java.util.*;

public class Contains {
    public static void main(String[] args) {
        List<String> stringList = new ArrayList<String>();
        stringList.add("someString");
        String val = new String("someString");
        if (stringList.contains(val)) {
            System.out.println("The value is in there");
        } else {
            System.out.println("There's no such value here");
        }
    }
}

【讨论】:

    【解决方案3】:

    这听起来不对:contains 使用equals 而不是==,所以如果字符串在列表中,应该可以找到它。这可以在ArrayList 使用的超类AbstractListindexOf 方法中验证。

    在您进行编辑后,请确保在执行 contains 之前使用 trim 字符串,否则它们可能包含 newline 字符。

    【讨论】:

      【解决方案4】:

      尝试以下方法,首先通过迭代列表并分别检查每个元素来使检查更加具体。比,当你击中你期望相等的元素时,这就是你应该看到的。检查它们是否真的相等。也许有一个案例差异? (或者其他一些难以捉摸但很明显的区别,比如空白?)

      【讨论】:

      • 谢谢,我实际上也在我的应用程序代码中使用了 trim()。鉴于所有的反应,我可以理解这可能是一个微小的差异,而不是一个根本问题。
      【解决方案5】:

      尝试重写equals(){},这样就可以指定哪个属性需要比较相等性....:P

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-28
        • 2014-09-10
        • 2018-11-15
        • 1970-01-01
        相关资源
        最近更新 更多