3

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?

Very Objective
  • 601
  • 7
  • 16
  • ```subSequence``` is not a ```String``` method, it's a ```CharSequence``` method. If you are dealing with ```String``` you should always use ```substring```. – zhh Aug 16 '18 at 07:09

3 Answers3

4

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
3

There's plenty of APIs where CharSequences are used instead of Strings - this happens when a CharSequence is "good enough" and the authors of the API believe that the elasticity added (e.g. possibility of aggressive optimization by using mutable implementations) overweight the benefit of safety offered by Strings.

A good, notable example is Android - almost all methods defined on widgets (see, for example, the TextView) that one would reasonably expect to take String - like setText - take a CharSequence instead.

So, of course, when an TextView needs to only take a part of the text, it will need to use the subsequence method.

fdreger
  • 12,264
  • 1
  • 36
  • 42
1

Is there really no benefit to using subSequence()?

-> I do not see any real benefit of that method. 

If so, why has it been introduced?

-> As per Java API note "This method is defined so that the  String class can implement the  CharSequence interface". As `CharSequence` has the abstract method CharSequence subSequence(int start, int end);
Amit Bera
  • 7,075
  • 1
  • 19
  • 42