Adding StringBuffer To TreeSet In Java

By | January 6, 2018

When you try to add StringBuffer/ StringBuilder to Treeset, exception will be thrown because StringBuffer and StringBuilder classes do not implement Comparable interface.

Points to Remember:

  • String class implements Comparable interface
  • StringBuffer class does not implement Comparable interface
  • StringBuilder class does not implement Comparable interface

The below code will throw an exception.

 
import java.util.*;
public class Test{
 public static void main(String[] args){
   Set<StringBuffer> s=new TreeSet<>();
    s.add(new StringBuffer("ABC"));
    s.add(new StringBuffer("XYZ"));
    System.out.println(s); 
 }
} 

Output:

Exception in thread “main” java.lang.ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable

at java.util.TreeMap.compare(TreeMap.java:1294)

at java.util.TreeMap.put(TreeMap.java:538)

at java.util.TreeSet.add(TreeSet.java:255)

at Test.main(Test.java:5)

Solution:

To add StringBuffer/ StringBuilder to TreeSet, you need to write a comparator class and override compare() method.

First convert both the StringBuffer objects to String like this:-

String s1=sb1.toString();

String s2=sb2.toString();

Because String class implements Comparable interface, you can directly use compareTo() method to compare two strings:

s1.compareTo(s2);

 
import java.util.*;
public class Test{ 
 public static void main(String[] args){
 Set<StringBuffer> s=new TreeSet<>(new ComparatorSB());
 s.add(new StringBuffer("ABC"));
 s.add(new StringBuffer("XYZ"));
 System.out.println(s);
 }
}
class ComparatorSB implements Comparator<StringBuffer>{
 
 @Override
 public int compare(StringBuffer sb1, StringBuffer sb2){
 String s1=sb1.toString();
 String s2=sb2.toString();
 return s1.compareTo(s2); 
 }
}

Output:

[ABC, XYZ]

Happy Learning 🙂

Leave a Reply