search

Home  >  Q&A  >  body text

java - Doubts about indexFor(int h, int length) in HashMap

 static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);
    }

HashMap will hash the hash value of the key and the size of the Entry[] array to obtain the subscript position of the Entry array. I just found out during debugging that there are two different keys (with different hash values), but after indexFor, I get The index subscripts are the same, which means that two values ​​with different key values ​​and different hash values ​​are strung together to form a linked list. I remember reading articles written by others before, and they all said that the hash values ​​are the same, but the key values ​​are different. Only 2 values ​​​​can form a linked list, but in actual debugging, I found different results. Can anyone please take a look at the problem

迷茫迷茫2775 days ago696

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-05-17 10:01:13

    Object (key) -> hashCode -> index
    

    DifferentObject可能有相同的hashCode(反过来一定不同,除非hashCodeequals定义错了);
    不同的hashCode可能有相同的index(and in turn must be different), only then will a linked list be formed.

    The hashCode可能跟你看到的某些文章的hash here doesn’t mean the same thing.

    reply
    0
  • Cancelreply