Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java contains doesn't work as expected because "someString" != "someString"

I want check whether a String value val is contained within a List of Strings lets call it stringList.

I am doing this

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

But it always seems to be that the value is not included. Is this because two String values that have the same characters are not actually equal? For a "home-made" class I could implement hashCode() and equals() and fix this, what can I do for String data?

EDIT:

The way I am getting val is outlined here:

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");
            }
        }
    }
}
like image 969
Ankur Avatar asked Sep 23 '12 11:09

Ankur


1 Answers

ArrayList.contains() uses Object.equals() to check for equality (hashCode() is not involved in List). This works well for strings. Probably, your string really isn't contained in the list...

You've probably overlooked some whitespace or upper/lower-case or encoding difference...

like image 105
Lukas Eder Avatar answered Nov 08 '22 14:11

Lukas Eder