Preface
In Java, equals () and hashcode () functions work closely together. If you design one of them, you need to design another one. In most cases, these two functions do not need to be considered. Simply use their default design. However, in some cases, it is best to design these two functions to ensure the entireProgram. The most common is that when an object is added to a collection object, these two functions must be designed by themselves. A more refined definition is: if you want to put an object a into another collection object B, or use this object A to find the key of a meta object in collection object B, it also supports the inclusion or deletion of meta objects in collection object B. Therefore, the equals () and hashcode () functions must be defined by the developer. In other cases, these two functions do not need to be defined.
Equals ():
It is used to compare two objects and compare object content. Of course, it can also be used to compare object reference values. What is the comparison of object reference values? It is worth comparing two variables. We all know that the value of a variable is actually a number, which can be seen as the code used to identify different objects. The comparison of two objects refer to the value, that is, the comparison of two numbers and two codents. This comparison is the default object comparison method. In the object, this method has been designed. Therefore, you do not need to rewrite it on your own, wasting unnecessary time.
The comparison of object content is the true purpose of designing equals (). the Java language has the following requirements for equals (), which must be followed. Otherwise, you should not waste time:
* Symmetry: If X. Equals (y) returns "true", then Y. Equals (x) returns "true ".
* Reflex: X. Equals (x) must return "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", as long as the content of X and Y remains unchanged, No matter you repeat X. "True" is returned for the number of equals (y) times ".
* In any case, X. Equals (null) always returns "false"; X. Equals (and X objects of different types) always returns "false ".
Hashcode ():
This function returns an integer code used for Hexi operations. Do not confuse this code with the Code represented by the variable mentioned above. The latter is not only a code, but also a function to find the object location in memory. The value returned by hashcode () is used to classify the location of an object in a specific collection object. These objects are hashmap, hashtable, hashset, and so on. This function and the above equals () function must be designed by yourself to assist hashmap, hashtable, hashset, and so on in searching and locating a large number of objects collected by yourself.
How do these collection objects work? Imagine that each meta-object hashcode is the encoding of a box. According to the encoding, each meta-object is included in the corresponding box according to the Code provided by hashcode. All the boxes add up to a hashset, hashmap, or hashtable object. When we need to find a meta object, we should first look at itsCodeThat is, the integer value returned by hashcode (). In this way, we find the box where it is located, and in the box, each metadata object is taken out one by one to compare with the object we are looking, if the content of the two objects is equal, our search will end. This operation requires two important information: The hashcode () of the object, and the comparison of the object content.
The relationship between the return value of hashcode () and equals () is as follows:
* If X. Equals (y) returns "true", the hashcode () of X and Y must be equal.
* If X. Equals (y) returns "false", the hashcode () of X and Y may be equal or different.
The reason for these two rules is actually very simple. For hashset, hashset can have one or more boxes, there can be one or more unique meta objects in the same box (the hashset must contain unique meta objects ). This example shows that a meta object can have the same hashcode as other meta objects. However, a metadata object can only be the same as a metadata object with the same content. Therefore, these two rules must be established.
Note the following when designing these two functions:
If the object type you designed does not use a collection object, you do not need to design the processing methods for these two functions. This is the correct object-oriented design method. Do not design any features that users cannot use at the moment, so as to avoid the trouble of function expansion in the future.
If you want to be specific during design and do not comply with the above two sets of rules, we recommend that you do not want to do anything you want. I have never met any developer or I said that designing these two functions violates the two rules mentioned above. When I encounter these violations, they are all handled as design errors.
When an object type is used as a collection object meta object, this object should have its own design for processing equals (), and/or processing hashcode, in addition, we must abide by the two principles mentioned above. Equals () First, check whether null is of the same type. The same type is checked to avoid the loss of exceptions such as classcastexception. Null is checked to avoid the loss of exceptions such as nullpointerexception.
If your object contains too much data, the two functions equals () and hashcode () will become less efficient. If the object has data that cannot be serialized, equals () may encounter an error in the operation. Imagine an object X, whose integer data type is transient (it cannot be converted into binary data streams by serialize ). However, equals () and hashcode () depend on this integer data. Is this object the same before and after serialization? The answer is different. Because the integer data before serialization is valid data, after serialization, the value of this integer data is not stored, and then converted from the binary data stream to the object, the statuses of the two (objects before and after serialization) are different. This is also worth noting.
1. When to rewrite equals ()
When a class has its own unique concept of "logical equality" (different from the concept of object identity ).
2. design equals ()
[1] use the instanceof operator to check whether the real parameter is of the correct type ".
[2] for each "key field" in the class, check the field value in the real parameter and the corresponding field value in the current object.
[2.1] for non-float and double primitive type fields, use = for comparison;
[2.2] recursively calls the equals method for the object reference domain;
[2.3] for float domains, use float. floattointbits (afloat) to convert to int, and then use = for comparison;
[2.4] for double fields, convert double. doubletolongbits (Adouble) to int and then use = for comparison;
[2.5] For array fields, call the arrays. Equals method.
3. When you rewrite equals (), you always need to rewrite hashcode ()
According to the equals method of a class (after rewriting), two different instances may be logically equal. However, according to the object. hashcode method, they are only two objects. Therefore, the violation of "equal objects must have equal hash codes ".
4. Design hashcode ()
[1] store a non-zero constant value, such as 17, in the result of the int variable;
[2] for each key field F in an object (each field considered in the equals method ):
[2.1] boolean type, computing (F? 0: 1 );
[2.2] Byte, Char, short type, calculation (INT );
[2.3] long type, calculation (INT) (f ^ (F >>> 32 ));
[2.4] float type, computing float. floattointbits (afloat );
[2.5] Double type, calculate double. doubletolongbits (Adouble) to get a long value, and then execute [2.3];
[2.6] references an object and recursively calls its hashcode method;
[2.7] array field, which calls its hashcode method for each element.
[3] Save the hash code calculated above to int variable C, and then execute result = 37 * result + C;
[4] Return result.
5. Example
The following class follows the above design principles and overwrites the equals () and hashcode () of the class ().
Package COM. ZJ. unit; import Java. util. arrays; public class unit {private short ashort; private char Achar; private byte abyte; private Boolean abool; private long along; private float afloat; private double Adouble; private unit aobject; private int [] ints; private unit [] units; Public Boolean equals (Object O) {If (! (O instanceof unit) return false; unit = (unit) O; return unit. ashort = ashort & unit. achar = Achar & unit. abyte = abyte & unit. abool = abool & unit. along = along & float. floattointbits (unit. afloat) = float. floattointbits (afloat) & double. doubletolongbits (unit. adouble) = double. doubletolongbits (Adouble) & unit. aobject. equals (aobject) & equalsints (unit. ints) & amp; compute sunits (Unit. Units);} private Boolean vertex sints (INT [] aints) {return arrays. equals (ints, aints);} private Boolean returns sunits (Unit [] aunits) {return arrays. equals (units, aunits);} public int hashcode () {int result = 17; Result = 37 * result + (INT) ashort; Result = 37 * result + (INT) achar; Result = 37 * result + (INT) abyte; Result = 37 * result + (abool? 0: 1); Result = 37 * result + (INT) (along ^ (along >>> 32); Result = 37 * result + float. floattointbits (afloat); long tolong = double. doubletolongbits (Adouble); Result = 37 * result + (INT) (tolong ^ (tolong >>> 32); Result = 37 * result + aobject. hashcode (); Result = 37 * result + intshashcode (ints); Result = 37 * result + unitshashcode (units); return result;} private int intshashcode (INT [] aints) {int result = 17; For (INT I = 0; I <aints. length; I ++) Result = 37 * result + aints [I]; return result;} private int unitshashcode (Unit [] aunits) {int result = 17; for (INT I = 0; I <aunits. length; I ++) Result = 37 * result + aunits [I]. hashcode (); return result ;}}
Note: This article is reposted at http://dev.firno?com/course/3_program/java/javajs/20090#/165034.html, which has been deleted and modified.