Java hashcode () method to interpret _java in detail

Source: Internet
Author: User
Tags set set

1.WHY hashcode ()?

The elements in set set are unordered and cannot be duplicated, so what is the basis for judging whether two elements are duplicated? "Comparing objects is equal, of course, with object.equal ()," said an ape. However, there are a large number of objects in set, and the number of object elements that are added to set set will gradually increase, greatly reducing the efficiency of program operation. In Java, hash algorithm (also called hashing algorithm) is used to solve this problem, the object (or data) is mapped directly to an address by a specific algorithm, and the access efficiency of the object is greatly improved. This way, when a collection set with a massive set of elements needs to add an element (object), by calling the element's Hashcode () First, you can navigate to the actual storage location of this element, and if there is no element in the location, the first time the object is stored in the set set, store the object directly in this location If an object exists in this position, call equal () to see if the two objects are equal, and the equality discards the element without saving, and hashes to other addresses.

2.HOW use Hashcode ()?

The Java language equal () has five requirements that must be followed for ape design.

of symmetry. If a.equal (b) returns "true", b.equal (a) must also return "true".
of the reflex. A.equal (a) must return "true".
Transitivity. If a.equal (b) returns "true" and B.equal (c) returns "true", C.equal (a) will return "true".
Consistency. If a.equal (b) returns "true", as long as a, B content does not change, no matter how many times a.equal (b) must return "true".
In any case, a.equals (null) returns "false" forever, and A.equals (and a different type of object) always returns "false."
The return value of the hashcode () and the Equals () relationship.

If A.equals (b) returns "true", then the Hashcode () of a and B must be equal.
If A.equals (b) returns "false", the Hashcode () of A and B may be equal or unequal.

Here is an example. In actual software development, it is best to rewrite both methods.

public class Employee {
  int    employeeId;
  String   name;

  Other methods would to @Override public
  boolean equals (Object obj)
  {
    if (obj==this)
      return true;
    Employee emp= (employee) obj;
    if (Employeeid.equals (Emp.getemployeeid ()) && name==emp.getname ()) return
      true;
    return false;
  }

  @Override public
  int hashcode () {
    int hash = 1;
    hash = hash * + employeeId;
    hash = hash * + Name.hashcode ();
    return hash;
  }
}

3. The following focuses on the common class of hashcode () implementation methods.

Hascode of String Class ()

public int hashcode () {
  int h = hash;
  if (h = = 0) {
    int off = offset;
    Char val[] = value;
    int len = count;

      for (int i = 0; i < len; i++) {
        h = 31*h + val[off++];
      }
      hash = h;
    }
    return h;
  }

The most interesting thing about this piece of code is the way the hash is implemented. The final computed hash value is:

S[0]31n-1 + s[1]31n-2 + ... + s[n-1]

S[i] is the first character of String, and n is the length of string. So why do we use 31 instead of other numbers?

31 is a singular prime, and if the multiplier is an even number and the multiplication overflows, the information is lost because multiplying with 2 is equivalent to a shift operation. The benefits of using primes are not obvious, but it is customary to use primes to compute hash results. 31 has a very good feature, is to use shift and subtraction instead of multiplication, can get better performance: 31*i== (i<<5)-I. Now the VM can automate this optimization. (from effective Java)

Hascode of object Class ()

Hashcode () in the object class is a native method. How does the native method call?

public native int hashcode ();

The native method class for the object class can be found here. For further analysis, please read another blog post

Static Jninativemethod methods[] = {
  {"hashcode",  "() I",          (void *) &jvm_ihashcode},
  {"Wait",    "(J) v",          (void *) &jvm_monitorwait},
  {"Notify",   "() v",          (void *) &jvm_monitornotify},
  { "Notifyall",  "() V",          (void *) &jvm_monitornotifyall},
  {"Clone",    "() ljava/lang/object;",  (void *) &jvm_clone},
};

The source code includes getclass () (LINE58) and so on, and Hashcode () (seen line43) is defined as a pointing jvm_ihashcode pointer.

Jvm.cpp defines the Jvm_ihashcode (line 504) function, which calls Objectsynchronizer::fasthashcode, which is set at Synchronizer.cpp, You can refer to the implementation of the Get_next_hash of line 576 Fasthashcode and 530 lines.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.