can StringBuffer objects be keys in TreeSet in Java?

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

    You are asking several questions:

    1. general question: "can you have a mutable key for a hash"
    2. Specific question: "Can StringBuffer be used as a key for a TreeSet"

    You have somethings confused and I will help you to sort them out

    There are 2 identifying strategies used with Maps in Java (more-or-less).

    1. Hashing: An input "Foo" is converted into a best-as-possible attempt to generate a number that uniquely accesses an index into an array. (Purists, please don't abuse me, I am intentionally simplifying). This index is where your value is stored. There is the likely possibility that "Foo" and "Bar" actually generate the same index value meaning they would both be mapped to the same array position. Obviously this can't work and so that's where the "equals()" method comes in; it is used to disambiguate

    2. Comparison: By using a comparative method you don't need this extra disambiguation step because comparison NEVER produces this collision in the first place. The only key that "Foo" is equal to is "Foo". A really good idea though is if you can is to define "equals()" as compareTo() == 0; for consistency sake. Not a requirement.

    Now to your general question:

    1. Can a key to a map be mutable. Answer: Yes, very very bad and dumb. Example: Map.put(k,v); k.modifyInternalHash(); Map.get(k) = null; // bad here
      In reality this happens through carelessness of hashing. Though this can occur with Comparative Maps it will be a much easier problem to diagnos.

    2. Can a StringBuffer be used as a key to a TreeMap/Set ? Yes. Use the alternative constructor: TreeSet(Comparator< T > comparator) and define your own comparison method for StringBuffer

    Good luck

提交回复
热议问题