One: The difference between string type=== and equals:
Conclusion: "==" is to determine whether the memory addresses of the two strings are equal, equals is to compare the values of the two strings are equal, specifically not to expand, interested students can visit the relevant blog.
String s1 = new String("java");
String s2 = new String("java");
System.out.println(s1==s2); //false
System.out.println(s1.equals(s2)); //true
In Java, equals and hashCode methods are the two methods provided in Object. string type rewrites equals() method and hashCode () method. The source code is as follows:
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; } /*Return the hash code, String's hash code is calculated in s [0] * 31 ^ (n-1) + s [1] * 31 ^ (n-2) +... + s [n-1]*/ 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; }
Second: the relationship between object equals and hashcode
Conclusion: When the equals() method of an object is rewritten, it is usually necessary to rewrite the hashCode() method to maintain the conventional agreement of the hashCode method, which states that the same object must have the same hash code. As follows:
(1) Two objects are equal, hashcode must be equal
(2) Two objects are different, hashcode is not necessarily different
(3) hashcode is equal and two objects are not necessarily equal
(4) hashcode is different, two objects must be different
Hashcode is used for fast access to hashed data. For example, when using HashSet/HashMap/Hashtable class to store data, the hashcode value of the stored object is used to determine whether it is the same or not. So if we rewrite euqals for an object, it means that as long as the member variables of the object are equal, euqals equals true, but not hashcode, then we rewrite a new object. When the original object. equals equals equals true, the hashcode of the two objects is different, which will lead to inconsistency of understanding.
Three: Using HashMap, if key is a custom class, you must rewrite hashcode() and equals()
When put element:
1. First, get hashcode according to the key of put element, and then calculate the subscript position of array according to hashcode. If there is no element in the subscript position, put the element directly.
2. If there are elements in the subscript position (i.e., hashcode calculated according to the key of the put element repeats), then the key object of the existing element and the put element needs to compare the equals method. If equals are different, it means that it can be put into the map. Here, because hashcode is the same, the subscript position of the array is the same. So a list is created at the location of the array, and the input element is put into the list header, and the original element moves backwards. _
B. When the get element:
Get the hashcode based on the key of the element, and then get the subscript position of the array based on the hashcode. If there is only one element, take it out directly. If the location is a linked list, the equals method needs to be called to traverse all elements in the linked list and compare them with the current elements to get the real object.
C. Benefits of hashcode:
If we do not use hashcode and use equals comparison directly, then we have 10w elements, put value or get value to compare 10w times. If we first judge by hashcode, our efficiency will be greatly improved.
We can compare the real life, if there is a teaching building, the first floor is grade 1, the second floor is grade 2, and so on, the sixth floor is grade 6, then we need to find the classroom of class 2, grade 5, through hashcode directly positioned to the fifth floor, and then find one on the fifth floor, so as to avoid looking from the first floor to one on the fifth floor.
4. Code demonstrates why hashCode methods must be rewritten when rewriting equals
After rewriting equals() and hashcode() with a student student class, the get() method of map returns the result of the value, which makes it clear why the hashCode method must be rewritten when rewriting equals.
package com.sinaif; public class Student { private String name; //Full name private String sex; //Gender private String idCard;//ID number Student(String name,String sex,String idCard){ this.name = name; this.sex = sex; this.idCard = idCard; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub if(obj == null){ return false; } Student obj1 = (Student)obj; if(this.name.equals(obj1.getName()) && this.idCard.equals(obj1.getIdCard())){ return true; } return false; } //@Override public int hashCode() { // TODO Auto-generated method stub String s= this.name + this.idCard; return s.hashCode(); } }
public static void main(String[] args) throws Exception { Map<Student,Student> map = new HashMap<Student,Student>(); Student s1 = new Student("haly","male","110200"); Student s2 = new Student("haly","female","110200"); map.put(s1, s1); System.out.println(map.get(s2)); // When there is no rewriting equals method and hashcode method, print null // When the equals method is overridden and hashcode method is not overridden, null is printed // When you override the equals method and the hashcode method, print out com.test.Student@95fb7d6 }