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

Ank*_*kur 4 java string contains list equals

我想检查字符串val列表中是否包含String值,并将其称为stringList.

我这样做

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

但似乎总是不包括价值.这是因为具有相同字符的两个字符串值实际上并不相等吗?对于"自制"类,我可以实现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");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Luk*_*der 10

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

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


Séb*_*nec 5

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

\n\n

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

\n