RFR (JDK11) 8137326: Methods for comparing CharSequence, StringBuilder, and StringBuffer

Jason Mehrens jason_mehrens at hotmail.com
Fri Jan 26 14:23:38 UTC 2018


1. Seems odd that StringBuilder and StringBuffer are comparable but don't have an equals/hashcode implementation.
Seems like if you are to stick with that you'll have to add the standard "natural ordering is inconsistent with equals" verbiage.
2. For StringBuffer compare, won't you have to either lock the 'another' object too so it is not mutated or perform some
sort of copy before compare? Neither sound like a good option.
3. Does CharSequence.compare need to specify that IndexOutOfBoundsException may be thrown under concurrent modification?
4. For CharSequence.compare, instead of creating a special case for string would it make sense to do:

if (cs1.getClass() == cs2.getClass() && cs1 instanceof Comparable) {
        return ((Comparable<Object>) cs1).compareTo(cs2);

Given #1 and #2 maybe StringBuilder and StringBuffer shouldn't implement comparable and just rely on users either calling
 'sb1.toString().compare(sb2.toString())' or 'CharSequence.compare(sb1, sb2)'.

From: core-libs-dev <core-libs-dev-bounces at openjdk.java.net> on behalf of Joe Wang <huizhe.wang at oracle.com>
Sent: Thursday, January 25, 2018 9:00 PM
To: core-libs-dev
Subject: RFR (JDK11) 8137326: Methods for comparing CharSequence, StringBuilder, and StringBuffer


Adding methods for comparing CharSequence, StringBuilder, and StringBuffer.

The Comparable implementations for StringBuilder/Buffer are similar to
that of String, allowing comparison operations between two
StringBuilders/Buffers, e.g.
aStringBuilder.compareTo(anotherStringBuilder). For CharSequence
however, refer to the comments in JIRA, a static method 'compare' is
added instead of implementing the Comparable interface. This 'compare'
method may take CharSequence implementations such as String,
StringBuilder and StringBuffer, making it possible to perform comparison
among them. The previous example for example is equivalent to
CharSequence.compare(aStringBuilder, anotherStringBuilder).

Tests for java.base have been independent from each other. The new tests
are therefore created to have no dependency on each other or sharing any

JBS: https://bugs.openjdk.java.net/browse/JDK-8137326
webrev: http://cr.openjdk.java.net/~joehw/jdk11/8137326/webrev/


More information about the core-libs-dev mailing list