Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Java, hashcode, equals and ==     - Eclipse installs support for Java 8 (Linux)

- Oracle 12c detailing the new features (Database)

- Two minutes thoroughly so that you understand Android Activity Lifecycle (Programming)

- Java JDK has been able to compile without warning (Programming)

- SQL Server memory Misunderstanding (Database)

- The minimum initial use of the Linux operating system RancherOS feelings (Linux)

- C language preprocessor command (Programming)

- Security Features Linux and Unix operating system, programming (Linux)

- Oracle SQL statement tracking (Database)

- What happens after the MySQL disk space is full (Database)

- Summary Linux operating system some tips to prevent attacks (Linux)

- Orabbix binding Python send graphical reports (Linux)

- Use Ansible efficient delivery Docker container (Server)

- Linux supports serial output method (Linux)

- How to find out a Unix system library files are 32-bit or 64-bit (Linux)

- The multiplexed signal driving IO (Programming)

- Oracle can not change the tablespace to backup mode in non-archive mode (Database)

- How Linux system password security guarantee (Linux)

- Attic-- delete duplicate data backup program (Linux)

- Install Jetty on CentOS / RHEL 6.X (Server)

  Java, hashcode, equals and ==
  Add Date : 2017-01-08      
  Hashcode method returns a hash code value for this object.

hashCode () method can be used to improve the efficiency of the search inside Map, Map based on different hashCode () to be placed in different positions Map search of an object when the first through hashCode () to find the appropriate location, and then according equals () method to determine the target position and the current object to be inserted is not the same. If two objects equals are equal, but not in a range, there is no opportunity for comparison, would be considered different objects.

So, Java for eqauls and hashCode methods so provides:

1, if two objects are the same, then their hashCode value must be the same, also tells us rewrite the equals method must be rewrite hashCode method;

2, the same as if the two objects hashCode, they are not necessarily the same

hashCode () and equals () is defined in the Object class, this class is the base class for all java, so all java classes inherit these two methods.

Noted earlier hashCode method has a native modifier, which means that the hashCode method is implemented by a non-java language described is a local method, its implementation is based on the local machine-dependent. Specific method is implemented in an external return address memory object.

/ **
    * Returns a hash code value for the object. This method is
    * Supported for the benefit of hashtables such as those provided by
    * < Code> java.util.Hashtable < / code>.
    * < P>
    * The general contract of < code> hashCode < / code> is:
    * < Ul>
    * < Li> Whenever it is invoked on the same object more than once during
    * An execution of a Java application, the < tt> hashCode < / tt> method
    * Must consistently return the same integer, provided no information
    * Used in < tt> equals < / tt> comparisons on the object is modified.
    * This integer need not remain consistent from one execution of an
    * Application to another execution of the same application.
    * < Li> If two objects are equal according to the < tt> equals (Object) < / tt>
    * Method, then calling the < code> hashCode < / code> method on each of
    * The two objects must produce the same integer result.
    * < Li> It is < em> not < / em> required that if two objects are unequal
    * According to the {@link java.lang.Object # equals (java.lang.Object)}
    * Method, then calling the < tt> hashCode < / tt> method on each of the
    * Two objects must produce distinct integer results. However, the
    * Programmer should be aware that producing distinct integer results
    * For unequal objects may improve the performance of hashtables.
    * < / Ul>
    * < P>
    * As much as is reasonably practical, the hashCode method defined by
    * Class < tt> Object < / tt> does return distinct integers for distinct
    * Objects. (This is typically implemented by converting the internal
    * Address of the object into an integer, but this implementation
    * Technique is not required by the
    * Java < font size = "- 2"> < sup> TM < / sup> < / font> programming language).
    * @return A hash code value for this object.
    * @see Java.lang.Object # equals (java.lang.Object)
    * @see Java.util.Hashtable
    * /
    public native int hashCode ();

In java class can override these two methods, the following are the String class in these two classes.

/ **
    * Compares this string to the specified object. The result is {@code
    * True} if and only if the argument is not {@code null} and is a {@code
    * String} object that represents the same sequence of characters as this
    * Object.
    * @param AnObject
    * The object to compare this {@code String} against
    * @return {@code True} if the given object represents a {@code String}
    * Equivalent to this string, {@code false} otherwise
    * @see #compareTo (String)
    * @see #equalsIgnoreCase (String)
    * /
    public boolean equals (Object anObject) {
    if (this == anObject) {
        return true;
    if (anObject instanceof String) {
        String anotherString = (String) anObject;
        int n = count;
        if (n == anotherString.count) {
        char v1 [] = value;
        char v2 [] = anotherString.value;
        int = offset;
        int j = anotherString.offset;
        while (n--! = 0) {
            if (v1 [i ++]! = v2 [j ++])
            return false;
        return true;
    return false;

/ **
    * Returns a hash code for this string. The hash code for a
    * < Code> String < / code> object is computed as
    * < Blockquote> < pre>
    * S [0] * 31 ^ (n-1) + s [1] * 31 ^ (n-2) + ... + s [n-1]
    * < / Pre> < / blockquote>
    * Using < code> int < / code> arithmetic, where < code> s [i] < / code> is the
    * < I> i < / i> th character of the string, < code> n < / code> is the length of
    * The string, and < code> ^ < / code> indicates exponentiation.
    * (The hash value of the empty string is zero.)
    * @return A hash code value for this object.
    * /
    public int hashCode () {
    int h = hash;
        int len = count;
    if (h == 0 && len> 0) {
        int off = offset;
        char val [] = value;

            for (int i = 0; i < len; i ++) {
                h = 31 * h + val [off ++];
            hash = h;
        return h;

String class equals is based on a comparison of content, rather than the more address-based.

Java language equals () requires the following, these requirements must be followed:

• Symmetry: If x.equals (y) returns is "true", then y.equals (x) should return a "true".

• reflex: x.equals (x) must return a "true".

• sexual analogy: If x.equals (y) returns is "true", and y.equals (z) returns is "true", then z.equals (x) should return a "true".

• there is consistency: If x.equals (y) returns is "true", as long as the x and y have the same content, whether you repeat x.equals (y) many times, returns are "true".

• In any case, x.equals (null), always returns a "false"; x.equals (and a different type of object x) always returns is "false".

When more than five points is to override equals () method, the guidelines must be followed, if the violation will be unexpected results, we must abide by.


java in ==, equals (), hashCode () and compare the objects are related to each of these three little use of it in java, java that is why the need to design comparison of these three objects it?

1. About ==

== It is easy to understand. java java is designed to compare two objects are not the same object.

For purposes of reference variables, when comparing two reference variables cited is not the same object, namely to compare two object references stored in the address is not the same.

For basic data types, the comparison is that the two data are not equal, no ambiguity.

Since the basic data types, there is no way, there is no equal () and hashCode () problem, the following discussion is for purposes of reference types.

2. With regard to equals ()

Why would design java equals () method?

== Comparison is whether the two objects are the same object, it does not meet many needs. Sometimes when two objects are ==, we still think that the two are "equal", such as the String object, when a string is a sequence of two objects has been, we think they are "equal" in . For such needs, we need to equals () to achieve. For this demand object's class, override its equals () method can be specific "equal" logic can be defined according to their own needs.

Need attention

Object in the equals () is the default implementation of == to compare two objects is not, that is, its effects and == is the same.

Some classes have been rewritten to provide java equals () method. Write your own classes if you need to realize their "equal" logic, you need to override equals () method.

3. With regard hashCode ()

Why design hashCode () method?

hashCode () method returns a value that we call hashCode it. From the name of the method can be seen, the aim is to generate a hash code. The main purpose is the hash code of the object at the time as a hash key input, thus it is easy to infer that we need each object hash code as different as possible, so as to ensure access performance hashing. In fact, the Object class provides default implementations for each object is indeed to ensure that different hash code (in memory address through a particular object on the basis of the algorithm returns a hash code).

Analysis to this place, seemingly no problem, the role of the three very clear, seems to have no relationship between them. On the java specification, hashCode () method and the equals () method can really does not matter.

but! ! ! ! ! ! ! ! there is a question.

Questions are as follows: For the collections HashSet, HashMap and classes and other related hash (HashSet as an example), through the hash algorithm to hash object. For HashSet, the object stored procedures: Depending on the object hash code, through the hash algorithm, find the object should be stored position, if that position is empty, the object is stored in that position; if this position is not empty, use equals () to compare objects and the object into the position, if the two are equal, no insert, if not equal, according to hash conflict resolution algorithm insert an object into another location.

The provision for java HashSet judgment is not duplicate objects is done by equals () method, which requires two objects equals () method of equal time, hash code must be equal (ie hashCode () Returns the value is equal). Suppose two objects equals () method of equal time, hash code is not equal, there will be equals () is equal to two objects are inserted in the HashSet, then allowed. Thus we have a look at the conclusions:

Conclusion: equals () is equal to two objects, the value of its hashCode () Returns must be equal

Through the above analysis, the conclusion is that there is no objection. Combined with the previous hash code as much as possible about the different requirements, has now become the equals () is equal to a certain object hash code is equal, and for equals () different objects to try to make a different hash code. So how can we ensure this?

4. rewrite hashCode ()

First, how to ensure "respect equals () equal to the object hash code must be equal."

equals () method to compare objects by comparing the object of all or part of the field to complete these fields is denoted by the set A, when if we calculate the hash code, if only selected portion of the field or all the fields from the set A It can be done, because the input is the same, no matter through what the algorithm must output the same (call the random function in the process? it belongs to eat a brace!). So designed to ensure that they meet the first requirement.

Secondly, equals () different objects to try to make hash codes.

For this guarantee it is to design a good algorithm, so that different input as possible to produce different outputs.

Here's details about how to design the algorithm. This algorithm is a ready reference, the specific steps of the algorithm is:

[1] to a non-zero constant value (generally the prime number), for example 17, is stored in the int variable result;

[2] (for each domain refers to the method considered equals) objects for each key field f:

[2.1] boolean type, calculate (f 0:? 1);

[2.2] byte, char, short type, calculate (int) f;

[2.3] long type, calculate (int) (f ^ (f >>> 32));

[2.4] float type, calculated Float.floatToIntBits (afloat);

[2.5] double type, the calculation Double.doubleToLongBits (adouble) to give a long, and then perform [2.3];

[2.6] object reference, the recursive call its hashCode method;

[2.7] array domain, each element of which call its hashCode method.

[3] save the above calculated hash code to the int variable c, and then perform result = 37 * result + c;

[4] return result.

In fact, their idea is: first go to a base, and then for each domain equals () are considered first converted into an integer, then execute result = 37 * result + c;
- Create the container and run the application Docker (Server)
- System with Windows Remote Desktop to connect Ubuntu 15.04 (Linux)
- Swift notes - let you two hours to learn Swift (Programming)
- Distributed transaction management Spring declarative transactions (Programming)
- Doubly linked list basic operations (Linux)
- IOwait Linux system monitoring diagnostic tools (Linux)
- linux system optimization and security configuration (Linux)
- Seven kinds of NIC binding mode Detail (Linux)
- How to use the DM-Crypt encryption Linux File System (Linux)
- Github inventory objects Algorithm (Linux)
- CentOS 7 install Hadoop-cdh-2.6 (Server)
- Hadoop new and old version of the difference in the size of the InputSplit (Server)
- Solaris 10 installation configuration mrtg monitoring system (Linux)
- MySQL multi-master-slave synchronization (Database)
- Restore Oracle Database Cold backup and database reconstruction emca (Database)
- Linux Nginx FastDFS integration module is installed Nginx and FastDFS (Server)
- The minimum initial use of the Linux operating system RancherOS feelings (Linux)
- Python-- for anomalies and reflection of objects articles (Programming)
- Android Studio Installation and Configuration Guide tutorial (Linux)
- How to use the ftp tool to transfer files between Windows and Linux (Linux)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.