JDK-8028757 : (spec str) CharSequence.subSequence improperly requires a "new" CharSequence be returned
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 8
  • Priority: P4
  • Status: Closed
  • Resolution: Fixed
  • Submitted: 2013-11-21
  • Updated: 2025-02-11
  • Resolved: 2013-12-03
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 8
8 b120Fixed
Related Reports
Relates :  
Relates :  
Description
The spec for CharSequence.subSequence says,

    Returns a new CharSequence that is a subsequence of this sequence.

This is overspecified. For String, subSequence should be allowed to return a pre-existing instance (such as 'this' or perhaps an interned string or something) as long as it has the right value.

This line of the specification was probably intended to apply to mutable CharSequences, as the mutability pretty much requires subSequence to return a new instance in order to avoid confusion. All the implementations of CharSequences in the JDK are mutable, except for String. [EDIT 2025-02-11: actually this doesn't apply to StringBuilder/StringBuffer, since their specifications for subSequence require returning a String object even though the declared return type is CharSequence. This does apply to CharBuffer though, and its spec is explicit about requiring return of a new CharBuffer.]

It might be reasonable to modify the spec to be something like this:

<< Returns a CharSequence that is a subsequence of this sequence. The returned sequence must be an instance such that mutation of this sequence or the returned sequence must not affect the value of the other. >>

This could be wordsmithed, of course. This pretty much has the effect of requiring mutable CS instances to return new copies, but String can return any instance it pleases since Strings are immutable.

Note that the current implementation of String.subSequence() simply calls String.substring(). This in turn returns 'this' if the substring range consists of the entire String. Thus, String.subSequence violates this specification, because it does not return a "new" CharSequence in some circumstances.
Comments
URL: http://hg.openjdk.java.net/jdk8/jdk8/jdk/rev/accd6ffd4b3f User: lana Date: 2013-12-10 18:28:32 +0000
10-12-2013

URL: http://hg.openjdk.java.net/jdk8/tl/jdk/rev/accd6ffd4b3f User: smarks Date: 2013-12-03 23:52:19 +0000
03-12-2013