can StringBuffer objects be keys in TreeSet in Java?

前端 未结 8 698
滥情空心
滥情空心 2020-12-21 15:18

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

相关标签:
8条回答
  • 2020-12-21 16:07

    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<String> sb=new TreeSet<String>();
        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);
    
    0 讨论(0)
  • 2020-12-21 16:12

    We are depending on the Default natural sorting order compulsory the object should be homogenous and comparable otherwise we will get run time exception saying Class cast exception. An object is said to be comparable if and only if Corresopding class implement the comparable interface. String class and all wrapper classes already implement a comparable interface but String Buffer class does not implement a comparable interface. Hence it will give class cost exception on the above code.

    0 讨论(0)
提交回复
热议问题