简体   繁体   English

Java 11中的CharSequence接口添加了方法`compare`。为什么不比较可比接口的`compareTo`?

[英]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 . CharSequence接口在Java 11中获得了一个新的静态方法: compare

This method returns an int : 此方法返回一个int

the value 0 if the two CharSequence are equal; 如果两个CharSequence相等,则值为0; a negative integer if the first CharSequence is lexicographically less than the second; 如果第一个CharSequence按字典顺序小于第二个,则为负整数; or a positive integer if the first CharSequence is lexicographically greater than the second. 如果第一个CharSequence按字典顺序大于第二个,则为正整数。

That sounds just like compareTo of Comparable . 这听起来就像compareToComparable Yet the Java team obviously chose to not make CharSequence extend Comparable . 然而,Java团队显然选择不让 CharSequence扩展Comparable Why not? 为什么不? The logic escapes me. 逻辑逃脱了我。

➥ What is it about CharSequence::compare that would not be an appropriate fit for Comparable::compareTo ? ➥有什么关于CharSequence::compare不适合Comparable::compareTo

Adding Comparable<CharSequence> wouldn't really work since String implements CharSequence and Comparable<String> . 添加Comparable<CharSequence>不会真正起作用,因为String实现了CharSequenceComparable<String>

For discussion, see this post by one of the OpenJDK developers regarding the subject. 有关讨论,请参阅OpenJDK开发人员之一关于该主题的这篇文章

Tip from that post: A method reference of the form CharSequence::compare would be suitable as a Comparator . 从该帖子提示: CharSequence::compare形式的方法引用适合作为Comparator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM