3

Hi i am trying to add StringBuffer object in treeset, but i got ClassCastException,because StringBuffer does not implement Comparable Interface, which String does. I would like to know the reason why StringBuffer and StringBuilder does not implement Comparable Interface implicitly.

TreeSet s = new TreeSet();
s.add(new StringBuffer("A"));
s.add(new StringBuffer("B"));
Avinash Solanki
  • 1,091
  • 1
  • 10
  • 19
  • 1
    Well, according to the docs, Comparable ` imposes a total ordering on the objects of each class that implements it. ` . I am not sure, how a class which implements the Builder pattern can really be sorted ... So for such cases, you should fall back to plain old String objects. – Dominik Sandjaja May 12 '15 at 19:56
  • 4
    They are mutable. It's hard to compare two things that are changing. – ZhongYu May 12 '15 at 19:56
  • Comparing two Strings is very common but I can't think of any situation where I have needed to compare two StringBuffers or StringBuilders. – nullPointer May 12 '15 at 19:56
  • 2
    Are you asking for the philosophical design tradeoffs argument the original creator(s) of StringBuffer/StringBuilder went through to decide whether or not to implement this interface? – arcy May 12 '15 at 19:57
  • 2
    If you really want to do that, you could use the constructor that accepts a `Comparator`. –  May 12 '15 at 20:00
  • Thanks for your help, it means we cant compare StringBuffer and StringBuilder directly,first we need to convert it to a String Object. – Avinash Solanki May 13 '15 at 05:53

0 Answers0