Equals method
- Use the = = operator to check whether the parameter is a reference to the current object, and if so, to return true directly;
- Use the instanceof operator to check if the parameter is the correct type. If not, return false directly. (depending on the logic, you may need to use = = To determine the Class);
- Converts the parameter to the correct type;
- For each critical field in the class, check to see if the field in the parameter matches the fish in the object. For base type fields that are neither float nor double, use = = Compare, use the Equals method for object reference fields, use Float.compare for float fields, and for double fields, use Double.compare
Note the point:
- When overriding equals, always overwrite hashcode;
- Do not replace the object parameter type in equals (Object obj) with another type.
hash function of the Hashcode method:
- Save a nonzero constant value, such as 17, in a variable of type int named result;
- Complete the following steps for each critical field F in the object, which refers to each domain that is involved in the Equals method:
- Computes the hash code C for the int type for the field:
- If the field is a Boolean type, the calculation (f?1:0);
- Evaluates (int) F If the field is a byte, short, char, or int type;
- If the field is a long type, the calculation (int) (f^ (f>>>32));
- If the field is of type float, the float.floattointbits (f) is computed;
- If the field is a double type, calculate Double.doubletolongbits (f), and then follow step 2.1.3 to calculate the hash value for the resulting long type;
- If the field is an object reference, and the Equals method of the class compares the domain by a recursive call to equals, then universal calls Hashcode for the domain recursively.
- If the field is an array, each element should be treated as a separate domain.
- Follow the formula below to merge the hash code C calculated in step 2.1 into result:
result = 31*result + C;
- return result
High-quality Equals method and Hashcode