I have the following code where I am trying to put StringBuffer objects as keys in a TreeSet. The reason I do this is to check if I can put mutable objects as keys. I am not getting a compilation error. but when I run this code, I get an error that is below the code. specifically, I get this java.lang.StringBuffer cannot be cast to java.lang.Comparable . what does this error indicate?
from javadoc I see that the StringBuffer class is declared final ( public final class StringBuffer ), does this mean that it is immutable and therefore hashable?
I am new to hashing and immutability, so please kindly help me here.
thanks
import java.util.*; class MutableKeys { public static void main(String[] args) { StringBuffer one = new StringBuffer("one"); StringBuffer two = new StringBuffer("two"); StringBuffer three = new StringBuffer("three"); Set<StringBuffer> sb=new TreeSet<StringBuffer>(); sb.add(one); sb.add(two); sb.add(three); System.out.println("set before change: "+ sb); one.append("onemore"); System.out.println("set After change: "+ sb); } } Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable at java.util.TreeMap.put(TreeMap.java:542) at java.util.TreeSet.add(TreeSet.java:238) at inheritance.MutableKeys.main
source share