Java Learning Four

Source: Internet
Author: User

Today in a station to see a programmer often make a mistake, is to write = =. This is a common mistake and is hard to spot. To avoid this error, I want to use equal instead of = =, but the basic type in Java does not support this method. and Java = = and equal are different.

= = comparison is a reference. Equal comparisons are also references, but for types such as String, Java overrides the method and compares the content. But the class that you define, the comparison or the reference.

For types such as string, equal compare content. For the class that you define, equal compares the reference.

The following paragraph is referring to others, about HashMap's hashcode.

Most of the classes in the API rewrite the Equals method, not the rewrite is generally their own writing class, if you define a class, the comparison of custom classes with equals and = = is the same, is the comparison handle address, because the custom class is inherited from Object, And the equals in object is realized with = =, you can see the source code.
You want to take HashMap's Value,hashmap by an object key. The way to work is to find the address in memory through the hashcode of your incoming object, When this address is found, then the Equals method is used to compare whether the contents of this address are the same as the one you put in, and the value is taken out.
So here's to match 2 parts, hashcode and equals but if you say you new object as key to take value is never the result, because each time new an object, the object's hashcode is always different, So we're going to rewrite hashcode, you can make your hashcode a constant in object, so you can always find the address of key through the hashcode of your object, and then you rewrite your Equals method to make the contents of the memory equal.

Java Learning Four

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.