java = =, Equals (), hashcode () Source Code Analysis

Source: Internet
Author: User

In Java programming or interview often encounter = =, equals () comparison. I looked at the source code, the actual programming summary.

1. = =

= = In Java is the address that compares two objects in the JVM. Better understand. Look at the following code:

1  Public classcomaddr{2      Public Static voidMain (string[] args)throwsException {3String S1 = "Nihao";4String s2 = "Nihao";5String s3 =NewString ("Nihao");6System.out.println (S1 = = s2);//true7System.out.println (S1 = = S3);//false8     }9}

In the code above:

(1) S1 = = S2 is true because both S1 and S2 are references to the string literal "Nihao", pointing to the same piece of address, so they are equal.

(2) S1 = = S3 is false because the object generated by new is in the heap, S3 is a reference to the variables in the heap, but S1 is a reference to the string literal "Nihao", and the address is different so it is not equal.

2.equals ()

Equals is a method in the root class Obeject. The source code is as follows:

 Public Boolean equals (Object obj) {    return ( this = = obj);}

The default Equals method is visible, calling = = directly, comparing the object address.

Different subclasses can override this method to make a judgment on the equals of two objects.

The Equals method overridden in the string class source code is as follows,

1      PublicBoolean equals (Object anobject) {2         if( This==anobject) {3             return true;4         }5         if(anobject instanceof String) {6String anotherstring =(String) anobject;7             intn =value.length;8             if(n = =anotherString.value.length) {9                 CharV1[] =value;Ten                 CharV2[] =Anotherstring.value; One                 inti =0; A                  while(n--! =0) { -                     if(V1[i]! =V2[i]) -                             return false; thei++; -                 } -                 return true; -             } +         } -         return false; +}

As you can see from the code above,

(1) equals in the String class first compares the address, and if it is a reference to the same object, the object is equal and returns true.

(2) If it is not the same object, the Equals method will compare the characters within the two string object, and return true only if it is exactly equal, otherwise false.

3.hashcode ()

  Equals is a method in the root class Obeject.

By default, Hashcode () in object returns the 32-bit JVM memory addresses of the objects. That is, if the object does not override the method, 32 of the corresponding object is returned as the JVM memory address.

The Hashcode method that is overridden in the string class source code is as follows

1  Public inthashcode () {2     inth = hash;//Default to 0 # # # # of private variables in the string class3     if(h = = 0 && value.length > 0) {//private Final char value[]; # # # Sting array of string contents saved in class4         CharVal[] =value;5 6          for(inti = 0; i < value.length; i++) {7H = * H +Val[i];8         }9hash =h;Ten     } One     returnh; A}

The string is immutable because it uses private final char value[];

Look at the following example, without overriding the class of the Hashcode method, directly returning the address of the 32-bit object in the JVM; the long class overrides the Hashcode method and returns the computed Hashcode value:

1  Public classcomhashcode{2      Public Static voidMain (string[] args)throwsException {3Comhashcode A =NewComhashcode ();4Comhashcode B =NewComhashcode ();5System.out.println (A.hashcode ());//8709196966System.out.println (B.hashcode ());//2987927207         8Long NUM1 =NewLong (8);9Long num2 =NewLong (8);TenSystem.out.println (Num1.hashcode ());//8 OneSystem.out.println (Num2.hashcode ());//8 A     } -}

Summarize:

(1) binding. when the Equals method is overridden, it is often necessary to override the Hashcode method to maintain the general contract of the hashcode method, which declares that the equality object must have an equal hash code.

(2) reason for binding. Hashtable implements a hash table, in order to successfully store and retrieve objects in the Hashtable, objects used as keys must implement hashCode methods and equals methods. Same as (1), the object must be guaranteed equal to equals, hashCode also equal. Because the hash table retrieves the object through Hashcode.

(3) default.

= = Compares the address of the object in the JVM by default.

  hashcode Default returns the storage address of the object in the JVM.

Equal compare objects, the default is to compare objects in the JVM address, with = =

Reference:

http://docs.oracle.com/javase/7/docs/api/

java = =, Equals (), hashcode () Source Code Analysis

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.