Java - TreeSet and hashCode()

前端 未结 4 1304
我在风中等你
我在风中等你 2020-12-03 14:20

I have a quick question about TreeSet collections and hashCode methods. I have a TreeSet and I\'m adding objects to it, before I add an object, I check to see i

相关标签:
4条回答
  • 2020-12-03 14:35

    You need to read Joshua Bloch's "Effective Java" chapter 3. It explains the equals contract and how to properly override equals, hashCode, and compareTo.

    0 讨论(0)
  • 2020-12-03 14:37

    From Java Doc:

    If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

    Means: the objects you use for hashing are not equal.

    0 讨论(0)
  • 2020-12-03 14:39

    You don't need to checked if it is contained, because the insert() basically does the same operation (i.e. searching the proper position) on its way to the insertion point. If the object can't be inserted (i.e., the object is already contained), insert returns false.

    0 讨论(0)
  • 2020-12-03 14:51

    TreeSet does not use hashCode at all. It uses either compareTo or the Comparator you passed to the constructor. This is used by methods like contains to find objects in the set.

    So the answer to your question is that your compareTo method or your Comparator are defined so that the two objects in question are considered equal.

    From the javadocs:

    a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.

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