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

我正在做这个

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

但这似乎总是不包含该值。这是因为两个具有相同字符的String值实际上不相等吗?对于“自制”类,我可以实现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");
            }
        }
    }
}

最佳答案

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

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

07-24 09:50
查看更多