About the hashcode and equals methods in Java

Source: Internet
Author: User

directly on the source!

public native int hashcode ();
/**
* Returns a hash code value for the object. This method is
* Supported for the benefit of hashes tables such as those provided by
* {@link Java.util.HashMap}.
* <p>
* The general contract of {@code hashcode} are:
* <ul>
* <li>whenever It is invoked on the same object more than once during
* An execution of a Java application, the {@code Hashcode} method
* Must consistently return the same integer, provided no information
* used in {@code equals} Comparisons on the object is modified.
* This integer need not remain consistent from one execution of
* Application to another execution of the same application.
* <li>if Objects is equal according to the {@code equals (Object)}
* method, then calling the {@code Hashcode} method on each of
* The objects must produce the same integer result.
* <li>it is <em>not</em> required that if the objects is unequal
* According to the {@link java.lang.object#equals (java.lang.Object)}
* method, then calling the {@code Hashcode} method on each of the
* objects must produce distinct integer results. However, the
* Programmer should is aware that producing distinct integer results
* For unequal objects may improve the performance of the hash tables.
* </ul>
* <p>
* As much as is reasonably practical, the Hashcode method defined by
* Class {@code Object} does return distinct integers for distinct
* Objects. (This was typically implemented by converting the internal
* Address of the object into a integer, but this implementation
* Technique is isn't required by the
* java&trade; Programming language.)
*
* @return A hash code value for this object.
* @see Java.lang.object#equals (java.lang.Object)
* @see Java.lang.system#identityhashcode
*/

Official documentation The first sentence says that the Hashcode method is primarily for hash tables, such as hashset,hashtable and HashMap, which store data in the form of a hash table (key Value), The hash value calculated by Hashcode can uniquely determine an element, and with the hash value it can quickly locate the element and improve the performance of the hash table. Here are some of the hashcode provisions:

    • In the same Java application, the return value should be the same as long as it is the same object, no matter how many times you call the Hashcode method. In different Java applications, this return value can be different.
    • If two objects are the same as judged by the Equals method, the return value of the two objects calling the Hashcode method must also be the same.
    • If two objects are not equal by calling the Equals method of the top-level parent Class (object), then the return value of each of the two objects calling the Hashcode method must be different.
    • However, as programmers, we can override this method in subclasses so that the two objects are equal as long as the values in the object are equal, but this can degrade the performance of the hash table. (according to the actual needs to determine whether to rewrite it)

For these reasons, the Hashcode method in the object class must return different values for different objects (this is determined by the internal conversion method, which is usually the actual address of the object in the JVM)

The value of the value must not be the actual location of the object is the address it! For example, the hashcode of 8 packaging classes

  wrapper class : Boolean Byte short Integer Long Character Float Doubles

Let's look at how they override the parent class's methods.

  Boolean@Override

public int hashcode () {
return Boolean.hashcode (value);
}

/**
* Returns a hash code for a {@code Boolean} value; Compatible with
* {@code boolean.hashcode ()}.
*
* @param value the value to hash
* @return A hash code value for a {@code Boolean} value.
* @since 1.8
*/
public static int Hashcode (Boolean value) {
return value? 1231:1237;
}
As you can see, the Boolean variable, which compares the Boolean value, if all is true, then returns 1231, if False, then returns 1237, which can be said as long as
is a Boolean object, so long as the values are the same, they are the same.

  Byte

 @Override 
Public int hashcode () {
return Byte.hashcode (value);
}

/**
* Returns a hash code for a {@code byte} value, compatible with
* {@code byte.hashcode ()}.
*
* @param value the value to hash
* @return A hash code value for a {@code byte} value.
* @since 1.8
*/
Publi c Static int hashcode (byte value) {
return (int) value;
}
for an object of type Byte, the value of Hashcode is the value after he is strongly converted to int type

Integer , and short is the same as the value converted to int type

Long
@Override
public int hashcode () {
return Long.hashcode (value);
}

/**
* Returns a hash code for a {@code long} value; Compatible with
* {@code long.hashcode ()}.
*
* @param value the value to hash
* @return A hash code value for a {@code long} value.
* @since 1.8
*/
public static int hashcode (Long value) {
return (int) (value ^ (value >>> 32));
}
The return value is either itself different from the number after the right shift of the symbol or the resulting value is strongly converted to type int.

  Character
Calling the Hashcode method of the object class directly
  Float
public static int hashcode (float value) {
return floattointbits (value);
}
public static int floattointbits (float value) {
int result = Floattorawintbits (value);
Check for NaN based on values of bit fields, maximum
Exponent and nonzero significand.
if ((Result & floatconsts.exp_bit_mask) = =
Floatconsts.exp_bit_mask) &&
(Result & floatconsts.signif_bit_mask)! = 0)
result = 0x7fc00000;
return result;
}public static native int floattorawintbits (float value);
The API says this: returns the hash code for this floating-point object. The result is an integer representation, as the method Floattointbits (float) produces, by the
The value of the original floating point represented by a floating-point object

  Double
Almost like the floate type.
The API says this: Returns the hash code for this double object. The result is a unique or two half-integer representation of two parts, entirely by method
Generated by Doubletolongbits (double)

through these words, it is clear that this method must not be divided with the Equals method . No, the source code is followed by the Equals method

public boolean equals (Object obj) {
return (this = = obj);
}
/**
* Indicates whether some other object is ' equal to ' this one.
* <p>
* The {@code equals} method implements an equivalence relation
* On Non-null object references:
* <ul>
* <li>it is <i>reflexive</i>: For any non-null reference value
* {@code x}, {@code x.equals (x)} should return
* {@code true}.
* <li>it is <i>symmetric</i>: For any non-null reference values
* {@code X} and {@code y}, {@code x.equals (y)}
* Should return {@code true} if and only if
* {@code y.equals (x)} returns {@code true}.
* <li>it is <i>transitive</i>: For any non-null reference values
* {@code x}, {@code y}, and {@code Z}, if
* {@code x.equals (y)} returns {@code true} and
* {@code y.equals (z)} returns {@code true}, then
* {@code x.equals (z)} should return {@code true}.
* <li>it is <i>consistent</i>: For any non-null reference values
* {@code X} and {@code y}, multiple invocations of
* {@code x.equals (y)} consistently return {@code true}
* or consistently return {@code false}, provided no
* information used in {@code equals} comparisons on the
* Objects is modified.
* <li>for any Non-null reference value {@code x},
* {@code x.equals (NULL)} should return {@code false}.
* </ul>
* <p>
* The {@code equals} method for class {@code Object} implements
* The most discriminating possible equivalence relation on objects;
* That's, for any non-null reference values {@code x} and
* {@code Y}, this method returns {@code true} if and only
* If {@code x} and {@code y} refer to the same object
* ({@code x = = y} has the value {@code true}).
* <p>
* Note that it's generally necessary to override the {@code hashcode}
* Method Whenever this method was overridden, so as to maintain the
* General contract for the {@code hashcode} method, which states
* That equal objects must has equal hash codes.
*
* @param obj the Reference object with which to compare.
* @return {@code true} If this object is the same as the obj
* argument; {@code false} otherwise.
* @see #hashCode ()
* @see Java.util.HashMap
*/

Direct comparison of two objects is not the same object

Here are the rules that override the Equals method to satisfy

  reflexivity : For any non-null reference x, you x.equals(x) should returntrue

  symmetry : For any reference to x and Y, if and only when y.equals(x) returned true , x.equals(y) should also returntrue

  transitivity : For any reference to X, Y, and Z, x.equals(y) the true y.equals(z) same result should be returned if returned

  consistency : Repeated calls x.equals(y) should return the same result if the objects referenced by x and Y have not changed

For any non-null reference x, you x.equals(null) should returnfalse

For variables of non-null reference types (without overriding equals and hashcode) they are equal if they point to the same address in the memory space. Overriding the Equals method is best to rewrite the Equals method, primarily to maintain the relationship with Hashcode (the same object must have the same hash value).

Several wrapper classes overriding the Equals method: File String Date 8 wrapper class, they compare types and content regardless of whether the reference is the same object,

Such as:

  The Equals method of String

public boolean equals (Object anobject) {
if (this = = AnObject) {
return true;
}
if (anobject instanceof String) {
String anotherstring = (string) anobject;
int n = value.length;
if (n = = anotherString.value.length) {
Char v1[] = value;
Char v2[] = Anotherstring.value;
int i = 0;
while (n--! = 0) {
if (v1[i]! = V2[i])
return false;
i++;
}
return true;
}
}
return false;
}
Compare the same object first, then compare the length, the last comparison value, if all satisfy the equal, then they are equal

Example :

public static void Main (string[] args) {
String str1 = "BB";
String str2 = str1;
String str3 = new String ("BB");
String STR4 = new String ("BB");

System.out.println (STR1==STR2);
System.out.println (STR2==STR3);
System.out.println (STR3==STR4);

System.out.println (Str1.equals (STR3));
System.out.println (Str3.equals (STR4));
}
Results:
True
False
False
True
True
Now, try the custom class.
  
public class Person {
Integer ID;
String name;
}
Then I didn't rewrite the Equals method
public static void Main (string[] args) {
Person Person1 = new person (1, "xiaoming");
Person Person2 = new person (1, "xiaoming");

System.out.println (Person1 = = Person2);
System.out.println (Person1.equals (Person2));
}
Results:
False
False
When I override the Equals method of the parent class
Print one More time
False
True
How do you rewrite equals and Hashcode ?

Most of the popular IDE has this function, of course, can also write their own, but I am lazy directly generated

@Override
public boolean equals (Object o) {
if (this = = O) {
return true;
}
if (o = = NULL | | getclass ()! = O.getclass ()) {
return false;
}

Person person = (person) o;

if (id! = null?!id.equals (person.id): Person.id! = null) {
return false;
}
return name! = null? Name.equals (person.name): Person.name = = null;
}

@Override
public int hashcode () {
int result = ID! = NULL? Id.hashcode (): 0;
result = * result + (name! = null? Name.hashcode (): 0);
return result;
}

Where the return value of Hashcode is custom, for example you can change 31 to 32

Tips: The understanding of the JVM after the two methods will be more thorough, combined with the source of food

About the hashcode and equals methods in Java

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.