I know subSequence returns a charSequence which is a read-only. Also, String class implements CharSequence. subString returns a String.
But, amongst subsequence and substring, when and which one to prefer
I know subSequence returns a charSequence which is a read-only. Also, String class implements CharSequence. subString returns a String.
But, amongst subsequence and substring, when and which one to prefer
From the API javadoc:
An invocation of this method of the form
str.subSequence(begin, end)
behaves in exactly the same way as the invocation
str.substring(begin, end)
And also:
This method is defined so that the String class can implement the CharSequence interface.
so, it is appropriate to use subSequence
when you are working with objects of type CharSequence
rather than String
You can always use substring
. The javadoc says the two have the same behavior. Although subSequence
returns a CharSequence
and substring
returns a String
, String
implements CharSequence
, thus you can always use substring
in contexts where a CharSequence
is required.
According to the javadoc, subSequence
is there because it has to be, in order to implement a method defined in CharSequence
. Since it's there because it's required and not particularly because there's a reason to use it, I don't see any reason to use it if you have a String
.
Here is a snippet from java.util.regex.Pattern.split
where String.subSequence
will be used if a String is passed as input arg:
public String[] split(CharSequence input, int limit) {
...
String match = input.subSequence(index, m.start()).toString();
...