Java basic knowledge trap (6)

Source: Internet
Author: User

Java basic knowledge trap (6)
I talked about equals and = last time. Today I want to know about this equals () and hasCode (). The last code is as follows: class Person {public String name; public Person (String name) {this. name = name;} public String getName () {return this. name ;}@ Override public boolean equals (Object anObject) {if (this = anObject) {return true;} if (anObject instanceof Person) {Person person = (Person) anObject; if (person. name. equals (this. name) {return true ;}} return false ;}this way can meet the requirements for comparing two simple objects, but we know that a set exists in java, For example, HashSet and HashMap, the two are slightly different in the judgment logic. For details, refer to the JDK source code. first look at the add source code of HashSet: public class HashSet <E> extends AbstractSet <E> implements Set <E>, Cloneable, java. io. serializable {static final long serialVersionUID =-5024744406713321676L; private transient HashMap <E, Object> map; private static final Object PRESENT = new Object (); public HashSet () {map = new HashMap <E, Object> ();} public boolean add (E e) {retur N map. put (e, PRESENT) = null ;}...........} we can see that when we use the add method of the HashSet object, actually the put method of the HashMap object is used internally, and its value is a constant of static final, it is certain that no matter how many are added, its value is directed to an object. Next let's take a look at the put Method of HashMap: public V put (K key, V value) {if (key = null) return putForNullKey (value); int hash = hash (key. hashCode (); int I = indexFor (hash, table. length); for (Entry <K, V> e = table [I]; e! = Null; e = e. next) {Object k; if (e. hash = hash & (k = e. key) = key | key. equals (k) {V oldValue = e. value; e. value = value; e. recordAccess (this); return oldValue;} modCount ++; addEntry (hash, key, value, I); return null;} private V putForNullKey (V value) {for (Entry <K, V> e = table [0]; e! = Null; e = e. next) {if (e. key = null) {V oldValue = e. value; e. value = value; e. recordAccess (this); return oldValue;} modCount ++; addEntry (0, null, value, 0); return null;} static int hash (int h) {h ^ = (h >>> 20) ^ (h >>>> 12); return h ^ (h >>>> 7) ^ (h >>> 4 );} static int indexFor (int h, int length) {return h & (length-1);} from some of the above calls, we can see that when put, we must first judge whether the key is null, if yes, use the putForNullKey () method to repeat the entire table array. Calendar, starting from subscript 0. If the object's key is null, the value is assigned and the old key is returned. Otherwise, it is directly added to the largest subscript. If the key is not null, calculate the hashCode to hash the key to find its position. If there is an object at the position, replace it with the current object and return the old value; otherwise, it is added directly and null is returned, indicating that the addition is successful. Here we can see that the hascode and equals methods of the object may be used when the HashSet or HashMap object is added. Therefore, the last time we rewritten the equals method, it cannot be a perfect solution, therefore, the hasCode method needs to be rewritten. The code for this modification is as follows: class Person {public String name; public Person (String name) {this. name = name;} public String getName () {return this. name ;}@ Override public boolean equals (Object anObject) {Boolean result = false; if (this = anObject) {result = true;} if (anObject instanceof Person) {Pers On person = (Person) anObject; if (person. getName (). equals (this. name) {result = true;} System. out. println (result); return result;} @ Override public int hashCode () {System. out. println ("hashCode"); return this. name. hashCode () ;}} public static void main (String [] args) throws Exception {Set <Person> set = new HashSet <Person> (); set. add (new Person ("www. luoliang. me "); set. add (new Person ("luoliang. Me "); set. add (new Person ("www. luoliang. me "); for (Iterator <Person> iter = set. iterator (); iter. hasNext ();) {System. out. println (iter. next (). getName () ;}} run the above result: hashCodehashCodehashCodetrueluoliang. mewww. luoliang. for the final output like me, we can also export the principle of when HashSet <String>: when an object is added to the Set, the Set calculator calculates the hashCode of the object to be added, according to the value to the storage location. When no object exists in the modified position, the set considers that the object does not exist in the set and adds it directly. When the modified position has an object, then, compare the objects to be added to the set with the objects to be changed to equals. If equals returns false, the set considers that this object does not exist and recalculates the hashcode to add it to the Set; if equals returns true, the set determines that the object already exists in the set and no longer adds the object to the set. Therefore, you must override the hashCode method when rewriting equals! Next we will summarize the relationship between HashSet and HashMap: HashSet is implemented using HashMap, key is the object to be put in, and value is an object constant. When the Add method is used, the underlying layer is to put an object into the Map, and its values are all the same and don't care! HashMap contains the Map. Entry set. At the underlying layer of HashMap, it is maintained using the table of the Entry array; The Entry implements MapEntry, while the Entry maintains the key, and the value and next call the add method is actually the put Method of HashMap, this put method will compare hascode and exuals. If they are the same, the old data value will be replaced and the old data value will be returned. This indicates that the replacement is successful, but the replacement is not added. If it is added differently and null is returned, the addition is successful! Using hascode to calculate the location will not change the time of the retrieved object with the size of the set or map, which will greatly improve the performance. First come here this time. Keep recording!

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.