can StringBuffer objects be keys in TreeSet in Jav

2019-01-29 03:13发布

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 not get any compile error. but when I run this code, I get the error that is below the code. specially, I get this java.lang.StringBuffer cannot be cast to java.lang.Comparable. what does this error indicate?

from javadoc I see that StringBuffer class is declared final (public final class StringBuffer), doesn't that mean it is immutable and hence hashable?

I am a newbie to the hashing and immutable stuff, so kindly help me out 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

7条回答
ゆ 、 Hurt°
2楼-- · 2019-01-29 03:55

The issue is that TreeSet sorts the items you put in it. Because StringBuffer doesn't implement Comparable, the TreeSet doesn't know how to sort them. You should pass in a Comparator when you create the TreeSet. Your comparator will tell the TreeSet how to sort the StringBuffers. Either that, or you can use a HashSet, which does not sort the elements.

As far as immutability goes: the final keyword on a class declaration means you can't subclass (extend) it. It does not, in and of itself, make the class immutable. Immutable means that the state of the object cannot be changed once it has been created. StringBuffers definitely can have their state changed after they are created, so they are not immutable.

查看更多
登录 后发表回答