János
János

Reputation: 35038

CharSequence equals() does not work well

Have this code:

if (cs.equals(keywordUnderProcess)) {

} else {

}

Both cs and keywordUnderProcess is CharSequence, has the value star, but the else case will execute. Why? equals check the value, isn't it?

enter image description here

enter image description here

Upvotes: 6

Views: 2764

Answers (3)

Fyodor Menshikov
Fyodor Menshikov

Reputation: 191

Since Java 11 (released in September 2018) there is a static method CharSequence.compare so you can use if (CharSequence.compare(cs, keywordUnderProcess) == 0) to compare two CharSequence-s for equality.

Upvotes: 2

Burak Gök
Burak Gök

Reputation: 340

You can use String#contentEquals if one the operands is a String. If not, you can first call toString() on one of them.

In the past, I have lost hours while debugging string equality problems and I am not satisfied by the justification in the API reference. As of Java 8, CharSequence could be defined as follows to allow arbitrary CharSequence's to be compared. Classes could then override the default implementation of equals(CharSequence) to increase performance, just like what String does in contentEquals().

public interface CharSequence {
    int length();
    char charAt(int index);
    CharSequence subSequence(int start, int end);
    
    default boolean equals(CharSequence s) {
        if (s == null || length() != s.length())
            return false;
        for (int i = 0; i < length(); i++)
            if (charAt(i) != s.charAt(i))
                return false;
        return true;
    }
}

Upvotes: 0

Matthew Diana
Matthew Diana

Reputation: 1106

If you read the javadoc page for the CharSequence interface, it says that the behavior for equals is undefined:

This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. It is therefore inappropriate to use arbitrary CharSequence instances as elements in a set or as keys in a map.

Upvotes: 7

Related Questions