Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 843
Basil Bourque Avatar asked Mar 14 '26 04:03

Basil Bourque


1 Answers

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.

like image 112
Plancke Avatar answered Mar 15 '26 17:03

Plancke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!