Hashcode is generated when the hashcode () method is called.

I'm a little confused as this question is asked in an interview, and I said this: "hashCode is generated for each object how and when it is created on the heap in the currently running application" "

but the interview said: "it is generated when we call the hashcode method on an object"

Moreover, I want to understand hashcode in more detail (and this also applies to java), please share some links / sources, since it is often asked in some interviews with interlocutors.

PS: when I do sysout ... on the object, the output comes as employee @ 942f533

+3
source share
3 answers

, . , . ,

   90        * As much as is reasonably practical, the hashCode method defined by
   91        * class {@code Object} does return distinct integers for distinct
   92        * objects. (This is typically implemented by converting the internal
   93        * address of the object into an integer, but this implementation
   94        * technique is not required by the ... [JDK]

http://www.docjar.com/html/api/java/lang/Object.java.html

, . , , , .

, , . , , , , , , , , , , .

+4

, - .

Hashcode , hashCode().

, , - java.lang.Object . , . HashMap, HashSet .. , - ..

java.util.HashMap:

public V get(Object key) {
    if (key == null)
        return getForNullKey();
    int hash = hash(key.hashCode());
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
            return e.value;
    }
    return null;
}

As you can see, it was used to get the correct object from the data structure.

If you check the comment of the hash code of the object, it also clearly mentions this

 * Returns a hash code value for the object. This method is 
 * supported for the benefit of hashtables such as those provided by 
 * <code>java.util.Hashtable</code>. 
0
source

All Articles