The equals () and hashcode () methods are inherited from the object class.
The equals () method equals () is defined in the object class as follows:
public boolean equals(Object obj) { return (this == obj); }
ObviouslyCompare the address values of two objects(That is, whether the comparison references are the same ). However, it must be clear that when the equals () method is used by these encapsulation classes, such as String, Math, Integer, and Double, the equals () method of the Object class is overwritten. For example, in the String class:
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 the content comparison, but it is no longer the address comparison. The Double, Integer, Math, and other classes in turn override the equals () method.Content Comparison. In addition, the basic types are used to compare values. There is nothing to say about this.
We should also note that the requirements of the Java language for equals () are as follows, which must be followed:
• Symmetry: If X. Equals (y) returns "true", then Y. Equals (x) returns "true ".
• Reflex: X. Equals (x) must return "true ".
• Analogy: 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", as long as the content of X and Y remains unchanged, No matter you repeat X. "True" is returned for the number of equals (y) times ".
• In any case, X. Equals (null) always returns "false"; X. Equals (and X objects of different types) always returns "false ".
The above five points are the rules that must be followed when the equals () method is rewritten. The hashcode () method is defined in the object class as follows:
public native int hashCode();
The description is a local method, which is implemented based on local machines. Of course, we can overwrite the hashcode () method in the class we write, such as string, integer, double, and so on. These classes all overwrite the hashcode () method. For example, the hashcode () method defined in the string class is as follows:
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 = 31*h + val[off++]; } hash = h; } return h; }
Explain this program (written in the string API ):
S [0] * 31 ^ (n-1) + s [1] * 31 ^ (n-2) +... + s [n-1]
The Int algorithm is used. Here, s [I] is the I character of the string, n is the length of the string, and ^ represents the power. (The hash code of the Null String is 0 .) If the two objects in the equals () and hashcode () relationships are equal, hashcode () must be equal; equals (), hashcode () may be equal; hashcode () is equal, equals () is not necessarily equal; hashcode () is not equal, and equals () is not equal. The main cause is the hash conflict in the hashcode () algorithm. Hashset, hashmap, and hashtablehashset are inherited from the set interface, and the Set interface implements the collection interface, which is a hierarchical relationship. So what principle does hashset use to access objects? Repeated objects are not allowed in hashset, And the element location is also unknown. In hashset, how does one determine whether the elements are repeated? In a Java set, the rule for determining whether two objects are equal is:
1), judge whether the hashcode of the two objects is equal
If they are not equal, the two objects are considered not equal.
If equal, transfer 2)
(This is only required to improve storage efficiency. In theory, it is not acceptable. However, if it is not, the actual usage of the aging rate will be greatly reduced. Therefore, we need it here. This issue will be highlighted later .)
2) determine whether two objects are equal using the equals operation
If they are not equal, the two objects are considered not equal.
If the two objects are equal, equals () is the key to determining whether the two objects are equal)
Why are there two principles? Can't I use the first one? No, because as mentioned earlier, the equals () method may not be equal when hashcode () is equal. Therefore, you must use the 2nd rules to ensure that non-repeating elements are added. The following code
Public static void main (String args []) {String s1 = new String ("zhaoxudong"); String s2 = new String ("zhaoxudong"); System. out. println (s1 = s2); // false System. out. println (s1.equals (s2); // true System. out. println (s1.hashCode (); // s1.hashcode () equals s2.hashcode () System. out. println (s2.hashCode (); Set hashset = new HashSet (); hashset. add (s1); hashset. add (s2);/* when adding s1 and s2, you can see that hashset considers s1 and s2 to be equal and that duplicate elements are added, so let s2 overwrite s1; */Iterator it = hashset. iterator (); while (it. hasNext () {System. out. println (it. next ());}}
At last, only a "zhaoxudong" is printed during the while loop ".
The output result is: false.
True
-967303459
-967303459
This is because the String class has already overwritten the equals () and hashcode () methods. Therefore, according to the above article 1.2, hashset considers them to be equal objects, added again. Let's look at the following example.
import java.util.*; 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; } }Output result:
1: zhangsan
1: zhangsan
3: wangwu
2: The lisi problem arises. Why does hashset add equal elements? Is this against the hashset principle? The answer is: no. The reason is that
Because when we compare the newly created student (1, "zhangsan") Objects Based on hashcode (), different hash code values are generated, so hashset treats it as a different object. Of course, the values returned by the equals () method also vary. So why does it generate different hash code values? Didn't we generate the same hash code when comparing S1 and S2? The reason is that we write our own student class.No new hashcode () and equals () MethodsSo during the comparison, it is the hashcode () method in the inherited object class. Haha, you still remember what the hashcode () method in the object class compares !!
It is a local method that compares the object address (reference address) and creates an object using the new method. The two generated objects are of course different, the result is that the values returned by the hashcode () of the two objects are different. Therefore, according to the first criterion, hashset treats them as different objects, and naturally does not need the second criterion for determination. So how can we solve this problem ?? The answer is: Re-hashcode () and equals () methods in the student class.
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; } }
Based on the override method, even if new student (1, "zhangsan") is called twice, when we obtain the object's hash code, according to the override method hashcode (), the obtained hash code must be the same.
Of course, based on the equals () method, we can also judge that it is the same. So they are treated as repeated elements when added to the hashset set. So when we run the modified program, we will find that the running result is:
1: zhangsan
3: wangwu
2: Lisi
We can see that the duplicate element problem has been eliminated.