Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java String Class implements Comparable Interface,but StringBuilder and StringBuffer does not Implements Comparable Interface [duplicate]

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
like image 340
eagertoLearn Avatar asked Sep 15 '26 10:09

eagertoLearn


1 Answers

just add a comparator class and then use it in your TreeSet as follows:

class Comparatorbuff implements Comparator<StringBuffer> {

        @Override
        public int compare(StringBuffer s1, StringBuffer s2) {
            return s1.toString().compareTo(s2.toString());

        }

}

in your main method: modify as follows
Set<StringBuffer> sb=new TreeSet<StringBuffer>(new Comparatorbuff());
like image 195
brain storm Avatar answered Sep 18 '26 01:09

brain storm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!