IdentityHashCode in HashMap's bucket

前端 未结 3 1199
眼角桃花
眼角桃花 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:27

    The bucket will use identityHashCode during insertion, but lookup uses only hash codes and compare() calls (if available). This means it sometimes needs to scan both subtrees of a node.

    The lookup logic looks line this

    do {
      if (... keys are equal or can be compared ...) {
        // Go left, right or return the current node
        ...
      } else if ((q = pr.find(h, k, kc)) != null)
        // Search the right subtree recursively
        return q;
      else
       // Go to the left subtree
       p = pl;
    } while (p != null);
    

    See http://hg.openjdk.java.net/jdk10/jdk10/jdk/file/ffa11326afd5/src/java.base/share/classes/java/util/HashMap.java#l1901 and note that tieBreakOrder() (the method responsible for comparing identityHashCodes is not invoked anywhere in find().

提交回复
热议问题