can StringBuffer objects be keys in TreeSet in Java?

前端 未结 8 723
滥情空心
滥情空心 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 sb=new TreeSet();
        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);
    

提交回复
热议问题