Java – Why is there three cases of greater than or equal to the hashcode of a key, and why do other cases occur?

Why is there three cases of greater than or equal to the hashcode of a key, and why do other cases occur?… here is a solution to the problem.

Why is there three cases of greater than or equal to the hashcode of a key, and why do other cases occur?

There is some code in java.util.HashMap.TreeNode#putTreeVal() as follows:

if ((ph = p.hash) > h)
    dir = -1;
else if (ph < h)
    dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
    return p;
else if ((kc == null &&
          (kc = comparableClassFor(k)) == null) ||
         (dir = compareComparables(kc, k, pk)) == 0) {
    if (!searched) {
        TreeNode<K,V> q, ch;
        searched = true;
        if (((ch = p.left) != null &&
             (q = ch.find(h, k, kc)) != null) ||
            ((ch = p.right) != null &&
             (q = ch.find(h, k, kc)) != null))
            return q;
    }
    dir = tieBreakOrder(k, pk);
}

There are two cases: h is less than ph and h is greater than ph.
Typically, code (pk = p.key) == k || (k != null && k.equals(pk)) Indicates that h is equal to ph, but I don’t know why there is else if after that.

What happens when the hashCode of two objects is equal, but == and euqlas() get false?

Does this cause this when Object’s class overrides the equals() method? But I’ve heard that rewriting equals() also has to rewrite hashCode(), so this problem doesn’t happen.

I wish someone could tell me which situation would lead to the third else if.

Solution

What is the situation when two objects’s hashCode is equals to each
other, but == and equals() will get false?

According to the Java documentation:

    If the objects are equal (i.e. x.equals(y) ==

  • true), then hashCode these objects should also be equal (i.e. x.hashCode() == y.hashCode()).
  • If two objects are equal hashCode (i.e.

  • x.hashCode() == y.hashCode()), then the objects do not enforce equality (i.e. x.equals(y) == true/false).

See Oracle Java Tutorial: Object as a Superclass

Related Problems and Solutions