IdentityHashCode in HashMap's bucket

前端 未结 3 1224
眼角桃花
眼角桃花 2021-01-04 19:33

In the implementation details of HashMap, I can read:

When using comparators on insertion, to keep a
 * total ordering (or as close as is requir         


        
3条回答
  •  情歌与酒
    2021-01-04 20:28

    The motivation for the identity hash code base tie breaking is explained right before the cited part:

    HashMap.java, line 212:

    * When bin lists are treeified, split, or untreeified, we keep 
    * them in the same relative access/traversal order (i.e., field 
    * Node.next) to better preserve locality, and to slightly 
    * simplify handling of splits and traversals that invoke 
    * iterator.remove. When using comparators on insertion, to keep a 
    * total ordering (or as close as is required here) across 
    * rebalancings, we compare classes and identityHashCodes as 
    * tie-breakers. 
    

    So, ordering by identity hash code provides a stable ordering to help implementing splitting and the Iterator.remove() operation (which must support continuing the traversal consistently).

    As explained in this answer, it is not used for lookup operations, as you already said in your question, two equal objects may have different identity codes. So for unequal objects having the same hash code and not implementing Comparable, there is no way around traversing all of them and probing via equals.

提交回复
热议问题