Andrii Abramov
Andrii Abramov

Reputation: 10773

Casting String to Charsequence

What is the purpose of casting String to CharSequence explicitly? String itself implements CharSequence interface.

Spring 4.x supports Java 6+ and CharSequence is present since 1.4.

Code snippet from Spring Framework:

public static boolean hasText(String str) {
    // Why do we cast str to CharSequence? 
    return hasText((CharSequence) str);
}

public static boolean hasText(CharSequence str) {
    if (!hasLength(str)) {
        return false;
    }

    int strLen = str.length();
    for (int i = 0; i < strLen; i++) {
        if (!Character.isWhitespace(str.charAt(i))) {
            return true;
        }
    }
    return false;
}

Upvotes: 2

Views: 4209

Answers (1)

user207421
user207421

Reputation: 311031

So that it won't recurse infinitely. The method could actually be removed. It is probably only there for backwards compatibility.

Upvotes: 5

Related Questions