String#subSequence() 有什么用

What uses are there for String#subSequence()

所以我阅读了 this answer and this answer 关于 subSequence()subString() 之间的区别,我了解到两者之间的唯一区别是 return 类型。事实上,subSequence() 在后台调用 subString()

另外,这个 article on subSequence 最后声明:

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

使用subSequence()真的没有好处吗?如果是这样,为什么引入它?如果有好处,它是什么以及它的已知用途是什么?

当适用于程序时,抽象会带来好处。例如:

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

这可以称为任何 CharSequence 实例(StringStringBuilderStringBuffer 等):

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

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

普通应用程序几乎不使用 CharSequence 接口,但这在某些情况下是适用的(尤其是库)。

写的意义不大:

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

因为通常需要 String 类型的子字符串,但框架可能更喜欢在其 API 中使用 CharSequence,而不是 String.

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);

有很多 API 在这里使用 CharSequences 而不是 Strings - 这种情况发生在 CharSequence 是 "good enough" 并且作者API 相信增加的弹性(例如通过使用可变实现进行积极优化的可能性)超过了字符串提供的安全性的好处。

一个很好的、值得注意的例子是 Android - 几乎所有在小部件上定义的方法(参见,例如 TextView)人们合理地期望采用 String - 比如setText - 改用 CharSequence

所以,当然,当一个TextView只需要取一部分文本时,就需要使用subsequence方法了。