Java improved Learning object (4)

Source: Internet
Author: User

Hash Code

Q: hashCode() What is the method used to do?

Answer: hashCode() method returns the hash code of this object to the caller (whose value is computed by a hash function). This method is commonly used in hash-based collection classes, like java.util.HashMap , java.until.HashSet and java.util.Hashtable .

Q: When overriding in a class equals() , why overwrite it at the same time hashCode() ?

A : overwriting at equals() the same time hashCode() can ensure that the function of the object is compatible with the hash set. This is a good habit, even if these objects are not stored in the hash collection.

Q: hashCode() What are the general rules?

Answer: hashCode() The general rules are as follows:

    • In the same Java program, the returned integers must be the same for an identical object, no matter how many times it is called, hashCode() hashCode() so equals() the content of the method comparison must be guaranteed to not change. However, you do not have to guarantee the same return value in another same Java program.
    • If two objects are the same as the result of a equals() method comparison, then the two object calls hashCode() should return the same integer value.
    • The equals() hashCode() returned integer value can be different when two objects use methods to compare the results of a different one. However, hashCode() different return values can improve the performance of the hash table.

Q: What happens if equals() I overwrite but not overwrite hashCode() ?

A : when overwriting equals() does not overwrite hashCode() , the problem occurs when storing objects in the hash collection. For example, refer to Code Listing 2.

Listing 2: equals() problems when the hash collection is only overwritten
1 import Java.util.HashMap;2 import Java.util.Map;3  4FinalclassEmployee5 {6    PrivateString name;7    Private intAge ;8  9Employee (String name,intAge )Ten    { One    This. Name =name; A    This. Age =Age ; -    } -   the @Override -     Publicboolean equals (Object o) -    { -   if(!(o instanceof Employee)) +  return false; -   +Employee e =(Employee) o; A   returnE.getname (). Equals (name) && e.getage () = =Age ; at    } -   - String getName () -    { -   returnname; -    } in   -    intgetage () to    { +   returnAge ; -    } the } *   $  Public classHashdemoPanax Notoginseng { -     Public Static voidMain (string[] args) the    { +Map<employee, string> map =NewHashmap<>(); AEmployee emp =NewEmployee ("John Doe", in); theMap.put (EMP,"First employee"); +System. out. println (Map.Get(EMP)); -System. out. println (Map.Get(NewEmployee ("John Doe", in))); $    } $}

Code Listing 2 declares a Employee class that overrides the equals() method but does not overwrite it hashCode() . A class is also declared HashDemo to demonstrate Employee the problem that will occur as a key store. the main() function First Employee creates a hashmap after instantiation, takes the Employee object as a key, and stores a string as a value. It then takes this object as a key to retrieve this set of merged output results. Similarly, by creating a new object with the same content Employee as the key to retrieve the collection, output the information.

Compile ( javac HashDemo.java ) and run ( java HashDemo ) code Listing 2, you will see the following output:

1 2 first employeenull

If the hashCode() method is correctly overwritten, you will see the second line first employee instead of null , because the two objects are the same as the result of the equals() method comparison, according to rule 2 above: If two objects are the same as the results of the equals() method comparison, Then the two object calls hashCode() should return the same integer value.

Q: How to properly overwrite hashCode() ?

Answer: Joshua Bloch's "Effective Java" Eighth edition gives a four-step approach to correct coverage hashCode() . The following steps are similar to the Bloch method.

  1. Declare a int variable of type, named result (or any other name you like), and initialize it to a nonzero constant (for example, 31). Using a non-zero constant affects all the initial hash values (the result of step 2.1) to a value of zero. "A nonzero value is used so, it'll be affected by any initial fields whose hash value (computed in Step 2.1) is zero . "If the initial result is the 0 case, the final hash value will not be affected by it, so the odds of the conflict will increase." This non-0 result value is arbitrary.
  2. for a specific value that is meaningful in each object (the equals() value involved in), the f following steps are processed:
    1. follow these steps to calculate the hash value of f based on the int type HC :
      1. for a boolean variable, HC = f? 0:1; .
      2. for a byte , char , short , or int type variable, HC = (int) f; .
      3. for a long variable, HC = (int) (f ^ (f >>> a)); . This expression evaluates the long variable as a 32-bit (the long has a maximum of 32 bits), and
      4. for a float type variable, HC = Float.floattointbits (f); .
      5. for a double type variable, long L = double.doubletolongbits (f); hc = (int) (l ^ (l >>>)); .
      6. For variables of reference types, if the equals () method in the class recursively calls the equals () class to compare member variables, then recursively call hashcode () ; If a more complex comparison is required, the "standard representation" of the value is calculated as the standard hash value of the foot, if the value of the reference type is null , f = 0 .
      7. for a reference to an array type, treat each element as a separate variable, call the corresponding method to calculate its hash value for each meaningful value, and then merge all the hashes as described in step 2.2.
    2. Calculations result = 37*result+hc , merging all the hc values into a hash value. Multiplication makes the hash value dependent on the rule of its value, which increases the discretization of the hash table when there are many similar values in a class.
    3. Returns the result.
    4. hashCode()When you are finished, make sure that the same object call hashCode() gets the same hash value.

To illustrate the above method, listing 3 is the second version of Code Listing 2, and its Employee class is rewritten hashCode() .

Code Listing 3: hashCode() overwriting correctly
1 import Java.util.HashMap;2 import Java.util.Map;3  4FinalclassEmployee5 {6    PrivateString name;7    Private intAge ;8  9Employee (String name,intAge )Ten    { One        This. Name =name; A        This. Age =Age ; -    } -   the @Override -     Publicboolean equals (Object o) -    { -       if(!(o instanceof Employee)) +          return false; -   +Employee e =(Employee) o; A       returnE.getname (). Equals (name) && e.getage () = =Age ; at    } -   - String getName () -    { -       returnname; -    } in   -    intgetage () to    { +       returnAge ; -    } the   * @Override $     Public inthashcode ()Panax Notoginseng    { -       intresult = to; theresult =Panax Notoginseng*result+Name.hashcode (); +result =Panax Notoginseng*result+Age ; A       returnresult; the    } + } -   $  Public classHashdemo $ { -     Public Static voidMain (string[] args) -    { theMap<employee, string> map =NewHashmap<>(); -Employee emp =NewEmployee ("John Doe", in);WuyiMap.put (EMP,"First employee"); theSystem. out. println (Map.Get(EMP)); -System. out. println (Map.Get(NewEmployee ("John Doe", in))); Wu    } -}

The class in code Listing 3 Employee declares two hashCode() values that are involved in both. The overridden hashCode() method is first initialized result to 31 , then String merges the hash values of the name variables of type and type into the, and int age result then returns result .

Compile ( javac HashDemo.java ) and run ( java HashDemo ) code Listing 3, you will see the following output:

1 2 first employeefirst employee

Java improved Learning object (4)

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.