The phone interview asked the HashMap class to implement what method, only know is to search by the hash value, so find efficient, other ask Sanbuzhi, now to study.
Want to study, but do not know where to start .... Sweat!!! Let's start with the semantics.
What is a hash value? Baidu a bit: The hashing algorithm maps a binary value of any length to a small binary value of a fixed length, a small binary value called a hash value. A hash value is a unique and extremely compact numeric representation of a piece of data ... I still don't see any relationship with the Java class ... It is also important that the hash table (also known as the hash list) is the hash function of the hash map, which is the hash algorithm, which is mapped to the hash value according to the key in the previous data structure. This hash function corresponds to Java, which is the Hashcode method in the object class:
According to the declaration of this method, the method returns a numeric value of type int and is a local method, so no specific implementation is given in the object class. (That is, the mapping from key to Hashcode is implemented by the class's own method ...) I thought it had something to do with HashMap. Dizzy dead ... )。 About the keyword native : The native keyword describes its method of modification as an original ecological method, and the corresponding implementation of the method is not in the current file, but in a file implemented in other languages such as C and C + +. The Java language itself cannot access and manipulate the underlying operating system, but other languages can be invoked through the JNI interface to enable access to the underlying. This brings up a new point of knowledge: JNI
Return to the point of study hashcode () method, now I have two questions: first, what is his specific role in the Java collection framework? Instead of the key being hashed by the hashcode () method, what is this key? First is the first question (the following section refers to this post: http://www.cnblogs.com/szlbm/p/5806226.html):
We know that for some collections of Java, such as set sets, the elements inside are not allowed to be duplicated. So when you insert an object into the collection, how do you determine if the object already exists in the collection? Perhaps most people would have thought of calling the Equals method to make comparisons on a case by case basis. However, if there are already 10,000 or more data in the collection, if the Equals method is used to compare each other, efficiency must be a problem. At this point the function of the Hashcode method is reflected, when the collection to add a new object, the first call the object's Hashcode method, to get the corresponding hashcode value, In fact, in the implementation of HASHMAP will use a table to save the hashcode value of the object that has been stored in, if the table does not have the hashcode value, it can be stored directly in, no further comparison, if there is a hashcode value, The Equals method that calls it is compared with the new element, the same is not saved, and the other addresses are hashed, so there is a conflict resolution problem, so the number of actual calls to the Equals method is greatly reduced. The Hashcode method in Java is to map the object-related information (such as the object's storage address, the object's field, and so on) into a numeric value, which is called a hash, according to certain rules. The following code is a concrete implementation of the Put method in Java.util.HashMap:
Publicv put (K key, V value) {if(Key = =NULL) returnPutfornullkey (value); inthash =Hash (Key.hashcode ()); inti =indexfor (hash, table.length); for(entry<k,v> e = table[i]; E! =NULL; E =e.next) {Object k; if(E.hash = = Hash && (k = e.key) = = Key | |Key.equals (k))) {V OldValue=E.value; E.value=value; E.recordaccess ( This); returnOldValue; }} Modcount++; AddEntry (hash, key, value, I); return NULL; }
The Put method is used to add a new element to the HashMap, and from the concrete implementation of the Put method, the Hashcode method is called to get the hashcode value of the element, and then see if the hashcode value exists in the table. If present, call the Equals method to re-determine if the element exists, update the value if it exists, or add the new element to HashMap. As can be seen here, the Hashcode method exists to reduce the number of calls to the Equals method, thus improving program efficiency.
After understanding the role of hashcode in the set frame, the remaining question, that is, the biggest question is: from the key through the Hashcode () method to hashcode this can be what? What is the default for generating a hash value? Does this hash value have anything to do with the object's address?
Some friends mistakenly think (like me) by default, Hashcode returns the object's storage address, in fact, this view is not comprehensive, indeed some JVMs are implemented to directly return the object's storage address, but most of the time it is not so, can only say that the storage address has a certain association. Here is the implementation of the hash hash value generated in the hotspot JVM:
StaticInline intptr_t get_next_hash (Thread *Self , oop obj) {intptr_t value= 0 ; if(Hashcode = = 0) { //This form uses an unguarded global Park-miller RNG,//So it's possible for both threads to race and generate the same RNG. //On MP system we'll have lots of RW access to a global, so the//mechanism induces lots of coherency traffic.Value =Os::random (); } Else if(Hashcode = = 1) { //This variation have the property of being stable (idempotent)//between STW operations. This can is useful in some of the 1-0//synchronization schemes.intptr_t addrbits = intptr_t (obj) >> 3 ; Value= addrbits ^ (addrbits >> 5) ^Gvars.stwrandom; } Else if(Hashcode = = 2) {Value= 1;//For sensitivity testing}Else if(Hashcode = = 3) {Value= ++gvars.hcsequence; } Else if(Hashcode = = 4) {Value=intptr_t (obj); } Else { //Marsaglia ' s xor-shift scheme with thread-specific state//This was probably the best overall implementation--we LL//Likely make this, the default in a future releases.unsigned t = self->_hashstatex; T^= (T << 11) ; Self->_hashstatex = self->_hashstatey; Self->_hashstatey = self->_hashstatez; Self->_hashstatez = self->_hashstatew; Unsigned v= self->_hashstatew; V= (v ^ (v >>)) ^ (t ^ (t >> 8)) ; Self->_hashstatew =v; Value=v; } Value&=Markoopdesc::hash_mask; if(value = = 0) value = 0xBAD ; assert(Value! = Markoopdesc::no_hash, "invariant") ; Tevent (hashcode:generate); returnvalue;}
so can you tell if two objects are equal directly based on the hashcode value? It is certainly not possible, because different objects may generate the same hashcode value. Although it is not possible to determine whether two objects are equal according to the Hashcode value, two objects can be judged directly from the hashcode value, and if the hashcode value of two objects is unequal, it must be two different objects. If you want to determine whether two objects are truly equal, you must pass the Equals method.
That is to say, for two objects, if the result of calling the Equals method is true, then the hashcode value of the two objects must be equal;
If the Equals method results in False, the hashcode value of the two objects may not be different;
If the hashcode value of two objects is not equal, the result of the Equals method must be false;
If the hashcode value of two objects is equal, the result of the Equals method is unknown
The point to note here is that in some cases, the programmer is designing a class to rewrite the Equals method, such as the string class, but it is important to note that the Hashcode method must be overridden while overriding the Equals method. This involves the hashcode () method being mapped by default. For basic data types, such as string,double, the default is to use its value as a parameter and then perform an operation to derive hashcode. For an object,hashcode defaults to returning the object's storage address in the JVM (not the actual physical memory address), which means that if the object does not override the method, 32 of the corresponding object is returned as the JVM memory address. After checking the JDK documentation, it was found that different classes implement hashcode methods differently. For our own defined classes, if we override the Equals method, the two objects are equal as long as the fields inside are equal. So when the collection is accessed, because it will first determine whether their hashcode is equal, the Equals method will be used to judge, so if we do not rewrite the Hashcode method, even if the two object field values consistent but because the address is different hascode different, Such a collection would not conclude that they were the same. So to rewrite the Hashcode method, let the Equals method and the Hashcode method always logically remain consistent.
Here, by the way, http://www.cnblogs.com/xudong-bupt/p/3960177.html some summary of this blog post:
The Hashcode () method in Java