can StringBuffer objects be keys in TreeSet in Java?

前端 未结 8 739
滥情空心
滥情空心 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 15:58

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

    class Comparatorbuff implements Comparator {
    
            @Override
            public int compare(StringBuffer s1, StringBuffer s2) {
                return s1.toString().compareTo(s2.toString());
    
            }
    
    }
    
    in your main method: modify as follows
    Set sb=new TreeSet(new Comparatorbuff());
    

提交回复
热议问题