简体   繁体   English

尝试在没有比较器的情况下添加树集时,StringBuffer 不会给出 ClassCastException

[英]StringBuffer not giving ClassCastException when trying to add in a treeset without Comparator

I was expecting the ClassCastException when trying to run the following piece of code:尝试运行以下代码时,我期待 ClassCastException:

 //  TreeSet<StringBuffer> t = new TreeSet<StringBuffer>((a, b) -> - 
  // a.toString().compareTo(b.toString()));
     TreeSet<StringBuffer> t = new TreeSet<StringBuffer>();
        Function<String, StringBuffer> f = s -> new StringBuffer(s);
        t.add(f.apply("A"));
        t.add(f.apply("M"));
        t.add(f.apply("B"));
        t.add(f.apply("Z"));
        t.add(f.apply("G"));
        System.out.println(t);

I have commented the Comparator code and was trying to use without the Comparator.我已经评论了 Comparator 代码并试图在没有 Comparator 的情况下使用。 But I am still getting the correct output.但我仍然得到正确的输出。 How is this possible because StringBuffer doesn't implement Comparable interface.这怎么可能,因为 StringBuffer 没有实现 Comparable 接口。 I am using Java 11. Was there any changes made in the later version related to this.我正在使用 Java 11。在更高版本中是否有与此相关的任何更改。

You are converting StringBuffer to String in comparator, andString class implements Comparable interface, And also as a note since from jdk-11 StringBuffer and StringBuilder also implements Comparable您正在比较器中将StringBuffer转换为String ,并且String类实现了Comparable接口,并且作为注释,因为从 jdk-11 StringBufferStringBuilder也实现了Comparable

(a, b) -> -a.toString().compareTo(b.toString())

But if you are on lower version below jdk-11 you will get the compile time error但是如果您使用的是低于 jdk-11 的较低版本,则会出现编译时错误

The method compareTo(StringBuffer) is undefined for the type StringBuffer方法 compareTo(StringBuffer) 未定义为 StringBuffer 类型

这是可能的,因为StringBuffer 确实实现了Comparable接口。

API Note: StringBuffer implements Comparable but does not override equals. API 注释:StringBuffer 实现了 Comparable 但不覆盖 equals。 Thus, the natural ordering of StringBuffer is inconsistent with equals.因此,StringBuffer 的自然顺序与 equals 不一致。 Care should be exercised if StringBuffer objects are used as keys in a SortedMap or elements in a SortedSet.如果 StringBuffer 对象用作 SortedMap 中的键或 SortedSet 中的元素,则应小心谨慎。 See Comparable, SortedMap, or SortedSet for more information.有关更多信息,请参阅 Comparable、SortedMap 或 SortedSet。 Since: 1.0 See Also: StringBuilder, String, Serialized Form https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StringBuffer.html#:~:text=StringBuffer%20implements%20Comparable%20but%20does,or%20elements%20in%20a%20SortedSet%20 .从:1.0 另见:StringBuilder, String, Serialized Form https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StringBuffer.html#:~:text =StringBuffer%20implements%20Comparable%20but%20does,或%20elements%20in%20a%20SortedSet%20

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

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