Java rewriting equals and hashcode considerations

Source: Internet
Author: User

Why rewrite equalsMust be rewritten when the hashCode

You may learn from a number of tutorials:

In Sun's official documentation, "If you redefine the Equals method, you must redefine the Hashcode method so that the user can insert the object into a hash (hash) table."

So what is SUN's consideration for making this rule?

In the collection framework, and all the data is stored in the form of a hash table, and the HashSet HashTable HashMap hashCode computed hash code is their identity card. The existence of a hash code can be:

    1. Quickly locates objects, improving the performance of the Hashtable collection.
    2. Only two objects can be judged equal if the index of the object in the hash table is hashCode equal to the object's property equals .
    3. As can be seen from the above, the hash code is mainly for the hash table service, in fact, if you do not need to use a hash table, you can not rewrite hashCode . But it should be because of the scalability of the program (in case you need to put the object into the Hashtable collection later), it will require rewriting equals at the same time hashCode to avoid unnecessary trouble in the subsequent development.
Rewrite equalsThe precautions

The Java language Specification requires equals the following features:

    1. reflexivity : For any non-null reference x, it x.equals() should be returned true .
    2. symmetry : For any reference to x and Y, y.equals(x) true x.equals(y) It should also be returned if and only if it is returned true .
    3. transitivity : For any reference to X, Y, and Z, x.equals(y) the true y.equals(z) same result should be returned if returned.
    4. Consistency : If the objects referenced by x and y do not change, repeated calls x.equals(y) should return the same result.
    5. For any non-null reference x, it x.equals(null) should be returned false .

In the case of object comparisons, how do we write a method that conforms to the feature equals , and the following recommendations are made in Core Java:

  1. The explicit parameter is named Otherobject, which is later converted to another variable called other.
  2. Detects if this and otherobject refer to the same object:

    if (Thisreturntrue;

    This equation can be calculated to avoid the comparison of the domain in the class, to achieve optimization.

  3. Detects if Otherobject is null and returns False if null. It is important to perform a non-null check.

  4. Compares whether this and otherobject belong to the same class.

    • If each subclass is rewritten equals , use the getClass check:
    if (GetClass ()! = Otherobject.getclass ()     ) return false
     
      
    • If all subclasses use the same, use a equals instanceof test:
    if instanceof ClassName))     return false;
  5. Converts the otherobject to the appropriate type variable.

    ClassName other = (ClassName) otherobject;
  6. You can now compare all the fields that need to be compared.

    • Basic type Usage == comparison
    • Object Usage equals Comparison
    • field of an array type can use static methods to Arrays.equals detect whether the corresponding array elements are equal
    • Returns True if all fields match

Note: when a subclass overrides a parent class equals method, it must completely overwrite the parent class method and cannot define a completely unrelated method because of a type error or other reason. You can use @Override annotations to mark methods that override the parent class so that the compiler detects errors in the overwrite process.

Rewrite hashCodeThe precautions

Hash code is an integer value exported by the object. Hash codes are not regularly generated by different algorithms in different objects, and the policy for generating hashcode in Java is (the following are excerpted from Java API 8):

    • The hashcode of the string class uses the algorithm to return a hash code based on its string content.

      Returns a hash code for this string. The hash code for a String object is computed as s[0]*31^ (n-1) + s[1]*31^ (n-2) + ... + s[n-1]

    • The hash code returned by the integer class is the integer value it contains.

      RETURNS:A hash code value for this object, equal to the primitive int value represented by this Integer object.

    • The hashcode of the object class returns the processed value of the memory address of the objects.

      Returns a hash code value for the object. This method was supported for the benefit of hash tables such as those provided by HASHMAP.

hashCodeWhat do you usually do if you want to rewrite it in your own class? It is recommended to combine the hash codes of the instance domains reasonably, so that the hash codes generated by different objects are more uniform. For example we now have an Cat object, it has name , size and color three different domains, then you can override the hashCode method as follows:

class Cat {    ...      Public int hashcode () {        ///Hashcode can return a negative value of return         6 * Name.hashcode ()             New Double (size). Hashcode ()             + Ten * color.hashcode ();    }    ......}

Of course there is a better way, we can call the static method directly Objects.hash and provide multiple parameters. This method is called on each parameter Object.hashCode and combines the returned hash code. Therefore, the above method can be abbreviated as:

 Public int hashcode () {    return  objects.hash (name, size, color);}

Note: equals hashCodethe definition must be identical, and two objects equals true must have the same hashCode . For example, if the definition equals compares the name of a kitten, it hashCode needs to hash the name instead of the employee's name or address.

Reference:

    • "Core Java" Volume One
    • "Hash table data Structure" "Deep Understanding hashcode & equals"

Java rewriting equals and hashcode considerations

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.