Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

hashset - can StringBuffer objects be keys in TreeSet in Java?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. The fact that StringBuffer is public final class StringBuffer means you can't subclass it. StringBuffer is quite mutable (that's the point, you can modify the contents of the buffer.)

  2. You don't want to use something that is mutable as the key because then after the object is modified, its equals() and hashcode() methods will return different results and you won't be able to find it in the Map anymore.

  3. If you really wanted to use StringBuffer in a TreeSet, you would have to provide your own Comparator since StringBuffer doesn't implement Comparable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...