Deep analysis _java programming of Java equals method and Hashcode method

Source: Internet
Author: User
Tags comparison hash

PS: This article uses jdk1.7
Analytical
Equals method for the 1.Object class

Copy Code code as follows:

/**
* 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>: to any non-null reference value
* {@code x}, {@code x.equals (x)} should return
* {@code true}.
* <li>it is <i>symmetric</i>: to any non-null reference values
* {@code X} and {@code y}, {@code x.equals (y)}
* Should return {@code true} if
* {@code y.equals (x)} returns {@code true}.
* <li>it is <i>transitive</i>: to 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>: to 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 is 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>
* The It is generally necessary to override the {@code hashcode}
* Method whenever this and is overridden, and so as to maintain the
* General contract for the {@code hashcode} method, which states
* That equal objects must have 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
*/
public boolean equals (Object obj) {
return (this = = obj);
}

Look at the code, the Equals method of object, using = = For comparison, just comparing the object reference, if the referenced object is the same, then return True.
Look at the annotation, the Equals method of object, with the following characteristics
1.reflexive-reflexivity
X.equals (x) return True
symmetry of 2.symmetric-
X.equals (y) return True
Y.equals (x) return True
3.transitive-transitivity
X.equals (y) return True
Y.equals (z) return True
X.equals (z) return True
4.consistent-Consistency
X.equals (Y) return true//So no matter how many times it's called, it's definitely returning true
5. Comparison with NULL
X.equals (NULL) return false//for None-null X object, returns false every time
6. Relationship with Hashcode
* The It is generally necessary to override the {@code hashcode}
* Method whenever this and is overridden, and so as to maintain the
* General contract for the {@code hashcode} method, which states
* That equal objects must have equal hash codes.
It's important to note that, in general, if you rewrite the Equals method, you must override the Hashcode method.
To ensure that objects with the same reference can have the same hashcode value
Well, see here, we understand why the Equals method is rewritten, and in general you need to rewrite the Hashcode method,
Although this is not mandatory, but if you can not guarantee the same reference object, no same hashcode, will leave a great risk to the system
equals method for the 2.String class
Copy Code code as follows:

/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument isn't {@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 = 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;
}

look at the source, we can find that this comparison is divided into two parts
1. Compare whether to refer to the same object first
2. If the reference object is different, whether two strings have the same content
The Hashcode method of 3,string class
Copy Code code as follows:

/**
* 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;
if (h = = 0 && value.length > 0) {
Char val[] = value;
for (int i = 0; i < value.length; i++) {
H = * H + val[i];
}
hash = h;
}
return h;
}

You can see that the hashcode formula is: s[0]*31^ (n-1) + s[1]*31^ (n-2) + ... + s[n-1]
Therefore, for the same string, the resulting hashcode must be consistent
In addition, for an empty string, the value of Hashcode is 0

Summary
Now we can make a summary of the questions at the beginning of this article.
1. What is the method used for string comparisons and how is the internal implementation? The
uses the Equals method to compare whether the reference is the same or to compare the content.

2.hashcode, and rewrite the equal method, why do you want to override the Hashcode method?
Hashcode is used by the system to quickly retrieve objects, and the Equals method is used to determine if the referenced object is consistent, so when the referenced object is consistent, you must ensure that its hashcode is also consistent, so you need to override the Hashcode method to ensure that the consistency

Related Article

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.