Is there a logical explanation why some methods in String class have parameters with CharSequence type and others with String type? For example:
public String replace(CharSequence target, CharSequence replacement)
and
public boolean startsWith(String prefix)
Why replace method does not use String for its parameters just like startsWith method does?
Is there a logical explanation why some methods in String class have parameters with CharSequence type and others with String type?
Short answer: Backwards compatibility.
CharSequence
was added in Java 1.4.
replace(CharSequence target, CharSequence replacement)
was added in Java 1.5, so it could use the already existing CharSequence
type.
startsWith(String prefix)
has existed since Java 1.0, so it couldn't use the non-existing CharSequence
type at the time, and couldn't be modified in Java 1.4 (or later) because that would cause backwards compatibility issues.
Why replace method does not use String for its parameters just like startsWith method does?
So you can pass other types of objects which implement CharSequence
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With