JAVA Hashcode Use method detailed _java

Source: Internet
Author: User

I. Introduction of the problem
When it comes to hashcode, you have to say the Equals method, both in the object class, because the object class is the base class for all classes, so you can override both methods in all classes.
To have a clearer understanding of the need to know the container Collection,set,list,map (key value can not be repeated), Set elements unordered not repeat, list elements orderly repeatable, then how the JVM determines the different elements?
Is it a comparison, that efficiency is too low, the JVM used the method of hashing (the hash address is not necessarily the actual physical address), to see if there is content on this address, not to think that there is no the same object ...
And look below the decomposition ...

Two. Problem analysis
First, the Equals () and hashcode () are inherited from the object class, and the Equals () method is defined in the object class as follows:

Copy Code code as follows:

public boolean equals (Object obj) {
return (this = = obj);
}

It is clear from the declaration that a comparison of the address values of two objects (that is, whether the comparison references are the same) is apparent. But we need to be clear, when string, Math, and Integer, Double .... These encapsulation classes, when using the Equals () method, have already overridden the object class's
Equals () method.

2. The second is the Hashcode () method, which is defined in the object class as follows:
public native int hashcode ();
Description is a local method, and its implementation is dependent on the local machine.

Copy Code code as follows:

public int hashcode () {
int h = hash;
if (h = = 0) {

NT off = offset;

Char val[] = value;

int len = count;

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


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

}

hash = h;
}
return h;
}


Explain this program: s[0]*31^ (n-1) + s[1]*31^ (n-2) + ... + s[n-1], you can see that the hash address is not necessarily the actual memory address.

3. A number of norms
If you override the Equals (object obj) method, it is necessary to rewrite the Hashcode () method to ensure that two objects that have the same hashcode () return value are judged by the Equals (object obj) method to be true. Simply put: "If two objects are the same, their hashcode should be equal". But note: This is just a spec, and if you're writing a class so that equals (Object obj) returns True and Hashcode () returns two unequal values, compile and run without error. This violates the Java specification, however, and the program buries the bug.
If equals (Object obj) returns false, which means that two objects are "not identical", it does not require that the hashcode () method be invoked on the two objects to get two different numbers (more to verify that the hash address is not necessarily the actual memory address). The simple point is: "If two objects are different, their hashcode may be the same."
According to these two norms, it is not difficult to obtain the following inference:
1, if the two objects Equals,java runtime environment will think that their hashcode must be equal.
2. If two objects are not equals, their hashcode may be equal.
3, if two objects hashcode equal, they are not necessarily equals (I understand because of the hash conflict).
4, if two objects hashcode not equal, they must not equals.

Three. Problem solving
Test the use of hashcode and equals methods ...

Copy Code code as follows:

Import Java.util.HashMap;
Import Java.util.Map;
Class A {

@Override
public boolean equals (Object obj) {

System.out.println ("Judge equals");

return true;
}

@Override
public int hashcode () {

SYSTEM.OUT.PRINTLN ("Judge Hashcode");

return 1;
}
}


public class Test {

public static void Main (string[] args) {

map<a,object> map = new Hashmap<a, object> ();

Map.put (New A (), New Object ());

Map.put (New A (), New Object ());


System.out.println (Map.size ());
}


}


Output:

Judge Hashcode
Judge Hashcode
Judge equals
2


The results are analyzed as follows:
As you can see, the JRE invokes the Hashcode () method of the new A () object. Where: The first line of "Judge Hashcode" printed out is the first time map.put (new A (), New Object ()) is printed. The next "Judgment hashcode" and "judgment equals" are printed by the second map.put (New A (), New Object ()). When the first map.put (New A (), New Object ()), obviously, this time is not the same, because there is nothing in this map, so the hashcode is not equal, there is no need to call the Equals (Object obj) method. When the second map.put (New A (), New Object ()), the JRE found two identical hashcode in the map (since I rewrote the hashcode () method of Class A to always return 1), it is necessary to call equals ( Object obj) method is judged. The two objects were then found to be not equals (because I overridden the equals (object obj) method and always returns false). At this point the judgment is over and the result is: two times the object is not the same. So the last time you print the length of the map, the result is: 2.

Four. A number of matters of note
We should also note that the Java language has the following requirements for Equals (), which must be followed:

Symmetry: If X.equals (y) returns "true", then Y.equals (x) should also return "true".
Reflectivity: X.equals (x) must return is "true".
Transitivity: If X.equals (y) returns "true" and Y.equals (z) returns "true", then Z.equals (x) should also return "true".
Consistency: if X.equals (y) returns "true", the return is "true" whenever the X and Y contents remain unchanged, no matter how many times you repeat X.equals (y).
In any case, x.equals (null), always returns "false"; X.equals (and X objects of different types) return forever false

The above five points is to rewrite the Equals () method, must comply with the criteria, if the violation will appear unexpected results, please be sure to comply with ...

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.