Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What uses are there for String#subSequence()

So I read this answer and this answer on the differences between subSequence() and subString() and I understand that the only difference between the two is the return type. In fact, subSequence() calls subString() under the hood.

In addition, this article on subSequence states at the end that:

There is no benefit in using subSequence method, ideally you should always use String substring method.

Is there really no benefit to using subSequence()? If so, why has it been introduced? If there is a benefit, what is it and what known uses are for it?

like image 919
Very Objective Avatar asked Feb 06 '26 20:02

Very Objective


1 Answers

There's the benefit of abstraction when that's applicable to a program. As an example:

public CharSequence getPrefix(CharSequence cs) {
    return cs.subSequence(0, 1);
}

And this can be called any CharSequence instance (String, StringBuilder, StringBuffer, etc.):

CharSequence cs = "John";
getPrefix("Name");

cs = new StringBuilder("James");
getPrefix(cs);

Normal applications hardly make use of the CharSequence interface, but that's applicable in some cases (libraries in particular).

It doesn't make much sense to write:

CharSequence sub = stringObject.subSequence(0, 1);

Because one normally expects a String-typed substring, but a framework may prefer to use CharSequence in its API, instead of String.

like image 169
ernest_k Avatar answered Feb 09 '26 10:02

ernest_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!