Skip to content
Advertisement

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:

 //  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. But I am still getting the correct output. How is this possible because StringBuffer doesn’t implement Comparable interface. I am using Java 11. Was there any changes made in the later version related to this.

Advertisement

Answer

You are converting StringBuffer to String in comparator, and String class implements Comparable interface, And also as a note since from jdk-11 StringBuffer and StringBuilder also implements 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

The method compareTo(StringBuffer) is undefined for the type StringBuffer

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement