Explanation of the differences between = = and Equals and hashcode in Java

Source: Internet
Author: User

One, the same point

are used to compare values or objects.

Two, different points

for "= =", for the base type (Char,byte,short,int,long,float,double,boolean), the comparison is the value, so is equal, for the reference object, compared to the referenced object's heap address, for example:

 Public class Main {   publicstaticvoidthrows  interruptedexception {      New  Object ();      New Object ();      = = obj2);}   }

Note For wrapper classes such as Integer, there are some special.

For the Equals () method, the method is a method of the object class, and when compared, the default comparison is also the memory address pointed to by the reference object, so the value is generally the same as the "= =" comparison, because Java does not support operator overloading, if I want two objects equal, Then you must override the Equals method. For string types, the method has been overridden, so it is equal to compare strings with equals.

For the Hashcode () method, the existence of hashcode is primarily for the sake of finding the shortcut, Hashcode is used to determine the storage address of the object in the hash storage structure. For example, HashMap is using hashcode to calculate which entry to deposit. The calculations for indexes in ROCKETMQ also take advantage of hashcode, for Hashcode () and Equals (), which are:

The hashcode of two objects is the same, and the object is not necessarily an object.

The hashcode of two objects is different, so it must not be the same hash object.

If two objects have the same equals, then the hashcode must be the same.

For Equals and Hashcode, if you override the Equals method, try overriding the Hashcode method as much as possible.

Explanation of the differences between = = and Equals and hashcode in Java

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.