Resolving the use of equals () and Hashcode () for Java objects

Source: Internet
Author: User

Resolving the use of equals () and Hashcode () for Java objects

Preface

In the Java language, the use of equals () and hashcode () two functions are tightly matched, and if you design one of them yourself, you should design the other one. In most cases, these two functions are not to be considered, so they can be used directly with their default design. In some cases, however, these two functions are best designed to ensure proper operation of the entire program. The most common thing is that when an object is added to the collection objects (collection Object), the two functions must be designed themselves. A more granular definition is if you want to put an object A into another collection object B, or use this object A to find the key where a meta object is in the collection object B, and to support whether to delete the objects in the collection object B, then Equals () and Hashcode () Functions must be defined by the developer themselves. In other cases, these two functions are not required to be defined.

equals ():

It is used for comparison of two objects, is a comparison of object content, and of course can be used to compare objects to see values. What is the comparison of object see values? That's two. See variables worth comparing, we all know that the value of the variable is actually a number, which can be regarded as the identification of different objects of the code. Two objects refer to the comparison of values, which is the comparison of two numbers, two codes. This comparison is the default method of object comparison, which is already designed in object. So you don't have to rewrite it yourself and waste unnecessary time.

The object content comparison is the true purpose of design equals (), and the Java language requirements for equals () are required to be followed. Otherwise, you shouldn't waste your time:
    • Symmetry: If X.equals (y) returns "true", then Y.equals (x) should also return "true".
    • Reflectivity: X.equals (x) must return is "true".
    • Analogy: If X.equals (y) returns "true" and Y.equals (z) returns "true", then Z.equals (x) should also return "true".
    • Consistency: if X.equals (y) returns "true", the return is "true" as long as the X and Y contents remain constant, no matter how many times you repeat X.equals (y).
    • In any case, x.equals (NULL) will always return "false", and X.equals (and X objects of different types) will always return "false".
hashcode ():
This function returns the integer code used for the operation of the Hutt, please do not confuse this code with the one described in the previous reference variable. The latter is not only a code name but also a function to find the location of an object in memory. The value returned by Hashcode () is used to classify the position of the object in some particular collection object. These objects are HashMap, Hashtable, HashSet, and so on. This function and the Equals () function above must be designed to assist HashMap, Hashtable, HashSet, etc. to search and locate a large number of objects that they collect.

How do these collection objects work, imagine each meta-object hashcode is a box of code, according to the code, each meta-object is based on the hashcode () provided by the code is classified into the corresponding box. All the boxes add up to be a hashset,hashmap, or Hashtable object, we need to look for a meta-object, first see its code, that is, the integer value returned by Hashcode (), so we find its box, and then in the box, every The meta-objects are taken out and compared to the object we are looking for, if the contents of two objects are equal, our search will be finished. This operation requires two important information, one is the object's Hashcode (), and the other is the result of the object content comparison.

The return value of Hashcode () is related to equals () as follows:
    • If X.equals (y) returns "true", then the Hashcode () of x and Y must be equal.
    • If X.equals (y) returns "false", then the Hashcode () of x and Y may be equal or unequal.


Why these two rules are this, the reason is very simple, take hashset, HashSet can have one or more boxes, in the same box can have one or more unique meta-object (HashSet must be a unique meta-object). This example shows that a meta object can have the same hashcode as other meta objects. However, a meta object can only be equal to a meta object that has the same content. So these two rules must be set up.

The two functions are designed to be noted:
If the object type you are designing is not used for collection objects, it is not necessary to design these two functions yourself. This is the right object-oriented design method, any user can not use the function, first do not design, in order to avoid the future expansion of the problem.

If you want to be creative in the design, do not abide by the above two sets of rules, then advised you still do not do such a fantasy thing. I have not met any developers and I said design these two functions to violate the previous two rules, I encountered these violations of the rules, is as a design error handling.

When an object type is a meta-object of a Collection object, the object should have its own design to handle equals (), and/or handle hashcode (), and abide by the two principles described earlier. Equals () first checks for null and whether it is the same type. Check the same type to avoid the occurrence of classcastexception such an exception to be thrown out. Null is to avoid the occurrence of nullpointerexception such an exception to be thrown out.

If your object contains too much data, then the two functions equals () and hashcode () will become inefficient. If the object has data that cannot be serialized, it is possible that the Equals () error occurs in the operation. Imagine an object x whose integer data is type transient (cannot be serialize into a binary data stream). However, equals () and hashcode () are dependent on this integer data, so is this object the same before and after serialization? The answer is not the same. Because the integer data before serialization is valid data, after serialization, the value of this integer data is not stored, and then re-converted from binary data flow to object, both (object in serialization The state of the previous and subsequent) has been different. This is also to be noted.

Knowing the above can help you:
1. Better design and development.
2. Conduct better test case development.
3. During the interview process, let the interviewer be satisfied with your knowledgeable.
Top
1

Resolving the use of equals () and Hashcode () for Java objects

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.