can StringBuffer objects be keys in TreeSet in Java?

前端 未结 8 740
滥情空心
滥情空心 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:49

    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.

提交回复
热议问题