How "contains()" method really work on List<string>?

rilent :

I am trying to check if two lists contain the same value and I can't figure out why one this specific value triggers my FileException

private static void checkFileHeaders(List<ColumnDefinition> columnsDefinitions, ArrayList<String> columnsName) throws FileException {
    for (ColumnDefinition cd : columnsDefinitions) {
        if(!columnsName.contains(cd.getFieldNameInFile())) {
            throw new FileException("Parameter "+cd.getFieldNameInFile() +" missing ");
        }
    }
}

As we can see in the debugger, my value exists in the list, can it be something with the encoding? It works with other values but not this specific one.

I am aware contains() works like equals() so what is wrong here

enter image description here

If I look at the individual characters :

cd.getFieldNameInFile() : [90, 66, 75, 80, 70, 45, 66, 85, 75, 82, 83]

columnsName[0] : [-1, -2, 90, 0, 66, 0, 75, 0, 80, 0, 70, 0, 45, 0, 66, 0, 85, 0, 75, 0, 82, 0, 83, 0]

How to solve this difference and what is the reason?

Daniel B. :

It checks for each element, if it is equal() to the element you are testing against.. Meaning, if the two elements pass the equals() method test, the contains() method will return true for them, if the equals() method returns false, so will the contains() method.

From the Java doc:

boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

Doc Link

https://docs.oracle.com/javase/8/docs/api/java/util/List.html#contains-java.lang.Object-

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143820&siteId=1