javacomparestring-comparisoncomparablecharsequence

CharSequence interface in Java 11 added method `compare`. Why not `compareTo` of Comparable interface?


The CharSequence interface gained a new static method in Java 11: compare.

This method returns an int:

the value 0 if the two CharSequence are equal; a negative integer if the first CharSequence is lexicographically less than the second; or a positive integer if the first CharSequence is lexicographically greater than the second.

That sounds just like compareTo of Comparable. Yet the Java team obviously chose to not make CharSequence extend Comparable. Why not? The logic escapes me.

➥ What is it about CharSequence::compare that would not be an appropriate fit for Comparable::compareTo?


Solution

  • Adding Comparable<CharSequence> wouldn't really work since String implements CharSequence and Comparable<String>.

    For discussion, see this post by one of the OpenJDK developers regarding the subject.

    Tip from that post: A method reference of the form CharSequence::compare would be suitable as a Comparator.