Java 包含不能按预期工作,因为 "someString"!= "someString"

标签 java string list equals contains

我想检查一个字符串值 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() 并解决这个问题,我可以为字符串数据做些什么?

编辑:

这里概述了我获取 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");
            }
        }
    }
}

最佳答案

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

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

关于Java 包含不能按预期工作,因为 "someString"!= "someString",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12552048/

相关文章:

java - 中缀到后缀程序不工作

java - 陷入 Spring MVC 新手教程

c# - 拆分字符串 - 通过多个字符,如 {1} {2} {3}

javascript - 搜索 HTML 文本区域中给出的单词,并使用 JavaScript 在字符串中突出显示它们

Python,使用列表理解

java - 如何在 java 编程中模板化 json

class - 如何将 java.lang.Class 对象打印到文件?

python - 基于列表创建多表 pyGTK 对象

.net - 链接列表的只读包装器。如何?

android - 如何在列表中创建列表?