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 sb=new TreeSet();
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);