I have the following code where I am trying to put the StringBuffer objects as keys in a TreeSet. The reason I do this is to see if I can put mutable objects as keys. I do n
TreeSet
takes only Comparable
objects where as StringBuffer
is not Comaprable
object.
TreeSet#add
Throws-ClassCastException - if the specified object cannot be compared with the elements currently in this set.
You can use String
object(Since String is Comparable) instead of StringBuffer
object.
For example:
Set<String> sb=new TreeSet<String>();
sb.add(one.toString());
sb.add(two.toString());
sb.add(three.toString());
System.out.println("set before change: "+ sb);
System.out.println("set After change: "+ sb);
We are depending on the Default natural sorting order compulsory the object should be homogenous and comparable otherwise we will get run time exception saying Class cast exception. An object is said to be comparable if and only if Corresopding class implement the comparable interface. String class and all wrapper classes already implement a comparable interface but String Buffer class does not implement a comparable interface. Hence it will give class cost exception on the above code.