Java combat equals () and Hashcode ()

Source: Internet
Author: User
Tags repetition set set

One. The Equals () method is detailed in the Equals () method, which is defined in the object class as follows:

Code

public boolean equals (Object obj) {

return (this = = obj);

}

It is clear that the address values of two objects are compared (that is, if the comparison reference is the same). But we know that String,

These encapsulation classes, such as Math, Integer, double, and so on, have overridden the Equals () Party of the object class when using the Equals () method

Method. For example, in the String class, the following:

Code

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 i = offset;

int j = Anotherstring.offset;

while (n–!= 0) {

if (v1[i++]! = v2[j++])

return false;

}

return true;

}

}

return false;

}

Obviously, this is a comparison of what is being done, and it is no longer an address comparison. The math, Integer, double, and so on.

Classes are overridden by the Equals () method, thus making a comparison of the content. Of course, the base type is a comparison of the values.


It should be noted that the Java language requirements for Equals () are as follows, and these requirements must be followed:

1. Symmetry: if X.equals (y) returns "true", then Y.equals (x) should also return "true".

2. Reflectivity: X.equals (x) must return is "true".

3. Analogy: If X.equals (y) returns "true" and Y.equals (z) returns "true", then Z.equals (x)

Should also return is "true".

4. Consistency: if X.equals (y) returns is "true", as long as the X and Y contents remain constant, no matter if you repeat x.equals (y) more

A few times, the return is "true".

5. In any case, x.equals (null), Return forever is "false"; X.equals (and X objects of different types) return forever

Is "false".

These five points are the criteria that must be adhered to when overriding the Equals () method, and unexpected results can occur if a violation occurs.

Two. Hashcode () method detailed

In the object class, Hashcode is defined as follows:

Code

public native int hashcode ();

The description is a local method, and its implementation is dependent on the local machine. Of course we can cover it in our own class.

Hashcode () methods such as String, Integer, double, and so on are all covered by the hashcode () method. For example, in string

The Hashcode () method defined in the class is as follows:

Code

public int hashcode () {

int h = hash;

if (h = = 0) {

int off = offset;

Char val[] = value;

int len = count;

for (int i = 0; i < len; i++) {

H = * H + val[off++];

}

hash = h;

}

return h;

}

Explain this program (written in the string's API): s[0]*31^ (n-1) + s[1]*31^ (n-2) + ... + s[n-1]

Using the int algorithm, where s[i] is the I-character of a string, n is the length of the string, ^ is the exponentiation (empty string

The hash code is 0).

To understand the role of hashcode, you must first know the collection in Java.

In general, there are two types of collections (Collection) in Java, one is list, and the other is set. Elements in the former collection

is ordered, elements can be duplicated, the latter elements are unordered, but the elements are not repeatable. This begs the question: to ensure that the element is not heavy

Complex, can two elements whether repetition should be judged by what?

This is the Object.Equals method. However, if each additional element is checked once, then when the element is many, add

The number of elements in the collection is much more numerous. That is, if there are now 1000 elements in the collection, then the 1001th one

When an element joins a collection, it calls the Equals method 1000 times. This obviously will significantly reduce efficiency.

Thus, Java uses the principle of a hash table. Hash (hash) is actually a personal name, because he proposes a hash algorithm concept,

So it was named after his name. The hashing algorithm, also known as the hashing algorithm, is to specify the data directly to an address according to the specific algorithm, the initial

Scholars can simply understand that the Hashcode method actually returns the physical address of the object store (which may not actually be).

In this way, when the collection is to add a new element, the Hashcode method of the element is called first, and then it can be positioned to

Placed on the physical location. If there are no elements in this position, it can be stored directly in this position without any further comparison.

, if there is already an element in this position, the Equals method that calls it is compared with the new element, and the same is not saved, not

Hash the other addresses in the same way. So there is a conflict resolution problem here. This will actually call the Equals method a large number of times

The big one is down, almost one or two times.

So, Java for the Eqauls method and the Hashcode method are defined as:

1. If two objects are the same, their hashcode values must be the same;

2. If the hashcode of two objects are the same, they are not necessarily the same (the objects mentioned here refer to the comparison by the Eqauls method).

If you do not do as required, you will find that the same object can appear in the set set, while the efficiency of adding new elements will greatly

Drop.

3.equals () equal to two objects, hashcode () must be equal, equals () not equal to two objects, but does not prove that he

Their hashcode () are not equal.

In other words, the Equals () method is not equal to two objects, and hashcode () may be equal (my understanding is that the hash code is in the raw

resulting in conflict). Conversely, hashcode () must be able to launch equals () also unequal; Hashcode () phase

Equals () may be equal or unequal.

In the object class, the Hashcode () method is a local method that returns the address value of an object, and the Equals () party in the object class

The method compares the address values of two objects, and if Equals () is equal, the two object address values are equal, of course hashcode ()

In the String class, Equals () returns a comparison of two object contents, and when two object contents are equal,

The Hashcode () method is based on the parsing of the rewrite code of the string class, and it is also known that hashcode () return results are also equal. And so on

It is also appropriate to know that the overridden equals () and Hashcode () methods in a wrapper class such as Integer and double are equally suitable for this principle. When

However, there are no overridden classes that follow this principle after inheriting the Equals () and Hashcode () methods of the object class.

Three. The close relationship between Hashset, Hashmap, Hashtable and Hashcode () and Equals () Hashset is the inherited set interface,

The set interface also implements the collection interface, which is a hierarchical relationship. Then the storage operations in HashSet, Hashmap, and Hashtable are the root

What is the principle for accessing objects? The following is an example of hashset, which we all know: repetition is not allowed in HashSet

object, the position of the element is also indeterminate. In the HashSet, how to determine whether the elements are duplicated? In the collection of Java, judge

The rules for whether two objects are equal are:

1. Determine whether the hashcode of two objects are equal

If it is not equal, the two objects are not equal, complete

If equal, transfer to 2

(This is only to improve storage efficiency requirements, in fact, it is not possible, but if not, the actual use of efficiency

will be greatly reduced, so we will do it as required here. )

2. Determine whether two objects are equal with the equals operation

If not equal, neither object is considered equal

If equal, two objects are considered equal (equals () is the key to determine whether two objects are equal)

Why is the two rule not to use the first one? No, because the front has said, Hashcode () is equal,

The Equals () method may also be unequal, so the 2nd guideline must be used to limit the inclusion of non-repeating elements.

Example 1:

Code

Package com.bijian.study;

Import Java.util.HashSet;

Import Java.util.Iterator;

Import Java.util.Set;

public class Hashsettest {

public static void Main (String args[]) {

string S1 = new String ("AAA");

String s2 = new String ("AAA");

System.out.println (S1 = = s2);

System.out.println (s1.equals (S2));

System.out.println (S1.hashcode ());

System.out.println (S2.hashcode ());

Set hashset = new HashSet ();

Hashset.add (S1);

Hashset.add (S2);

Iterator it = Hashset.iterator ();

while (It.hasnext ()) {

System.out.println (It.next ());

}

}

}

Operation Result:

Text Code Collection Code

False

True

96321

96321

Aaa

This is because the string class has overridden the Equals () method and the Hashcode () method, so HashSet thinks they are equal to the

The image has been added repeatedly.

Example 2:

Code

Package com.bijian.study;

Import Java.util.HashSet;

Import Java.util.Iterator;

public class Hashsettest {

public static void Main (string[] args) {

HashSet hs = new HashSet ();

Hs.add (New Student (1, "Zhangsan"));

Hs.add (New Student (2, "Lisi"));

Hs.add (New Student (3, "Wangwu"));

Hs.add (New Student (1, "Zhangsan"));

Iterator it = Hs.iterator ();

while (It.hasnext ()) {

System.out.println (It.next ());

}

}

}

Class Student {

int num;

String name;

Student (int num, String name) {

This.num = num;

THIS.name = name;

}

Public String toString () {

return num + ":" + name;

}

}

Operation Result:

Text Code Collection Code

1:zhangsan

3:wangwu

2:lisi

1:zhangsan

Why does hashset add equal elements, and is this a violation of HashSet's principles? The answer is: No. Because in

Different hash codes are generated based on hashcode () comparison of two established new Student (1, "Zhangsan") objects

Value, so hashset treats him as a different object, and of course the value returned by the Equals () method is not equal.


Why would a different hash code value be generated? Do we not generate the same hash code when comparing S1 and S2? Reason

Is that the student class we wrote ourselves did not re-hashcode () and the Equals () method, so in comparison, it was inherited

The Hashcode () method in the object class, and the Hashcode () method in the object class is a local method that compares the address of the object

(referring to address), using the new method to create the object, two times generated is of course different objects, resulting in the result is two objects

The values returned by Hashcode () are not the same, so hashset treats them as different objects.

How to solve this problem? The answer is: Re-hashcode () and the Equals () method in the student class.

Code

Class Student {

int num;

String name;

Student (int num, String name) {

This.num = num;

THIS.name = name;

}

public int hashcode () {

Return num * Name.hashcode ();

}

public boolean equals (Object o) {

Student s = (Student) o;

return num = = S.num && name.equals (s.name);

}

Public String toString () {

return num + ":" + name;

}

}

Operation Result:

Text Code Collection Code

1:zhangsan

3:wangwu

2:lisi

You can see that the problem of repeating elements has been eliminated, depending on the overridden method, even if the new is called two times

Student (1, "Zhangsan"), when we get the hash code of the object, according to the overridden Method Hashcode (), obtain the hash code Ken

Is the same, of course, according to the Equals () method we can also judge the same, so when adding to the HashSet collection, treat them as

Repeating elements were regarded.

Rewrite the Equals () and Hashcode () Summary:

1. The focus is equals, rewriting the hashcode is just a technical requirement (to improve efficiency)

2. Why do you want to rewrite equals? Because in the Java collection framework, the two objects are judged equal by equals.

3. In Hibernate, the set collection is often used to hold related objects, and set collections are not allowed to be duplicated. In the HashSet set

When you add an element in a hop, you can actually rewrite the Equals () clause as well. But when the elements in the hashset are relatively long, or are rewritten

When the Equals () method is more complex, we only use the Equals () method to make comparison judgments, and the efficiency is very low, so we introduce

Hashcode () This method is just to improve efficiency, and this is very necessary. For example, it can be written like this:

Code

public int hashcode () {

return 1; Equivalent to hashcode invalid

}

The effect of this is to compare the hash code when it is not judged, because each object returns a hash code of 1, each time must be

It is necessary to compare the Equals () method before the judgment is repeated, which of course leads to a significant reduction in efficiency.


Technology sharing: www.kaige123.com

This article from the "11247808" blog, reproduced please contact the author!

Java combat equals () and Hashcode ()

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.