On hashCode

"Java programming ideas" in the description of hashCode is:

Design hashCode (when the most important) factor is: whenever, calling hashCode the same object () should produce the same value. If you produce a hashCdoe when added to a HashMap object with the put () () value, and use get () out Shique had another hashCode () value, then it can not regain the object a. So if you hashCode () method relies on the variable data object, the user must be careful, because this data changes, hashCode () method will generate a different hash codes, is generated corresponding to a different key.

1. HashCode source code analysis

1.1 Object of the source code HashCode
public int hashCode() {
    int lockWord = shadow$_monitor_;
    final int lockWordStateMask = 0xC0000000; // Top 2 bits.
    final int lockWordStateHash = 0x80000000; // Top 2 bits are value 2 (kStateHash).
    final int lockWordHashMask = 0x0FFFFFFF; // Low 28 bits.
    if ((lockWord & lockWordStateMask) == lockWordStateHash) {
        return lockWord & lockWordHashMask;
    }
    //返回的是对象引用地址
    return System.identityHashCode(this);
}
 
The source code 1.2 String HashCode
public int hashCode() {
    int h = hash;
    if (h == 0 && count > 0) {
        for (int i = 0; i < count; i++) {
   //String.hashCode multiplication and addition using
            H + H * = 31 is the charAt (I);
        }
        the hash = H;
    }
    return H;
}
 
The source code 1.3 Integer HashCode
int the hashCode public () {
    // int value
    return value;
}

2. HashCode brought doubt
Why override equals Also rewrite hashCode?
What hashCode that?
hashCode role?
What hash code (hash value) is a?
hash table (hash table) What is?
hashCode method has the benefit of hash table?
hashCode method of hash is not beneficial to you?

2.1 What is a hash, how hash value generated.

Translation hash do "hash" is the value of the input of arbitrary length, () function is a fixed length message digest output by the hash. there are many hash functions, comprising: a direct method modulo multiplication rounding method, middle-square method and so on.

hash table is what? hash table is a hash value thereof.

HashCode role:

For example: hashcode there are 7, 8, of such position.

 

HashCode presence of primarily for fast lookup, is HashCode (position in the hash table is used to represent objects HashCode) to determine the memory address of the object in the hash storage structure.

    Such as: store 1000 number, stored in the 900, 900 on the first traverse if already stored, to traverse 900 times, if not stored, it will consume a lot of time. If a hash is stored as a hash table has 1,2,3,4,5,6,7,8 such a position. If the number 100 has been stored, when the storage hashcode is 1, then there are 20 numbers and his hashcode same, only we need to follow the 20 digits compared to (use equals), if not the same, it is stored in a location 1. By contrast with the original method to know hashcode has a great advantage.

   Why use it equals method, when an object to find the time because there may be more than one value for each location to store the hash table, then how to determine whether the current target object is to find it, this time we need to use the equals method.
3 .HashCode role
Reduce the number of lookups, to improve program efficiency
For example, to find out if there are duplicate values
h (k1) ≠ h (k2 ) is k1 ≠ k2
first looks h (k2) output value (memory address) to see if the memory address exists value;
if not, indicates that the value of the retry value is not present;
if so, compare the value, it means that the same hash value already exists in the list, if not the same then a comparison of a value; and without having to start a comparative value, reducing the number of lookups
 
 
4.HashMap in HashCode
Similarly, in Java, the main role is to fit hashCode method based on a set of hashes with the normal operation of such a set of hashes comprises HashSet, HashMap and HashTable.
Why do you say? Consider a situation when inserting objects to the collection, how to determine whether the object already exists in the collection? (Note: do not allow the collection of repeat element exists)
Perhaps most people would think to call the equals method to compare one by one, this method does work. However, if the data collection ten thousand or more of the data already exists, if the equals method to compare one by one, efficiency is necessarily a problem.
In this case the role of the hashCode method manifested, when set to add a new object, first call hashCode method this object, corresponding to a value obtained hashcode, actually stored in the table with a particular implementation has the deposit into HashMap hashcode value of an object, if not the hashcode value table, it can be stored directly into, without any further compare; hashcode if the value exists, it will be called the equals method to compare the new element, if not identical saved, not the same as other addresses on the hash, so there is a conflict resolution problem here, so that the actual number of calls equals method is greatly reduced, and said plainly: hashCode method in Java is based on certain rules information related to the object (such as a memory address of the object, a field object, etc.) is mapped into a numerical value, this value is referred to as a hash value. The following code is put in the specific implementation of the method java.util.HashMap:

put method is used to add new elements to a HashMap, seen from the realization put method will first call hashCode hashCode method to get the value of the element, and then see if the hashCode value table, if there equals method is called again determine whether the presence of the element, if present, is updated value value, otherwise it will add a new element to the HashMap. As can be seen from this, the presence of hashCode method is to reduce the number of calls equals method to improve the efficiency of the procedure.
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
 
5. hashcode may be directly determined whether the two objects are equal
Certainly not because of different objects may generate the same hashcode value. Although not determine whether two objects are equal according hashcode value, but can be determined directly from the two objects ranged hashcode value, if the value of two objects hashcode unequal, then there must be two different objects. To determine if two objects are really the same, it must be the equals method.
That is for the two objects, if the equals method invocation result obtained is true, the two objects must be equal hashcode values;
If the results obtained by the method equals false, the two objects are not necessarily different values hashcode;
if two objects ranged hashcode value, equals the result obtained by the method is necessarily false;
equal hashcode value if the two objects, the the results obtained by the method equals unknown.
6. In an example HashSet hashCode () action
Assumptions, HashSet already has 1000 elements. When inserting the first 1001 elements need to how to deal with?
Because HashSet is a collection of Set, which allows duplicate elements. "1001 will be the first element-by-element 1000 and earlier to compare"?
Obviously, this is equal to the low efficiency. Hash good solution to this problem, which calculates the position of the element in the hash table based on the hash code element, then the element can be inserted into the location. For the same elements, nature is only saved one.
It can be seen, when the two elements are equal, their hash code must be equal; but the reverse is not necessarily correct. In the hash table,
1, if the two objects are equal, then their hashCode () value must be the same;
2, if two objects hashCode () are equal, they are not necessarily equal.

Guess you like

Origin www.cnblogs.com/cdlyy/p/12169291.html