I. Role of hashcode ()
Hashcode () is used to calculate the hash value. When storing data, if there are thousands of data records, each time a data is stored, it needs to be stored multiple times, which is very inefficient, use Hash ValueAlgorithmAfter the hash value is obtained, it is divided into different regions based on the hash value, which greatly reduces the number of comparisons and improves efficiency. :
2. Comparison of arraylist_hashset and hashcode Analysis
To add a type to a hashset in a custom class, you must override the hashcode and equlas methods to determine whether the elements are repeated. When determining whether the elements are consistent, call the hashcode method first. If the hash value is the same, then call the equals method to continue comparison and determination. If the hash value is different, the equals method is no longer called for determination.
Note: The hash value is the same. The two objects are not necessarily equal. The two objects are equal. The hash values of these two objects must be equal.
Memory leakage: the object does not need to be used again, but does not reference it and is not recycled.
SeeCode:
Public class reflectpoint {public int X; Public int y; Public reflectpoint (int x, int y) {super (); this. X = x; this. y = y;} Public String tostring () {return this. X + "" + this. Y ;}@ overridepublic int hashcode () {final int prime = 31; int result = 1; Result = prime * result + X; Result = prime * result + Y; return result ;}@ overridepublic Boolean equals (Object OBJ) {If (this = OBJ) return true; If (OBJ = NULL) retu Rn false; If (getclass ()! = Obj. getclass () return false; Final reflectpoint Other = (reflectpoint) OBJ; If (X! = Other. X) return false; If (y! = Other. Y) return false; return true ;}}
Public class reflecttest1 {public static void main (string [] ARGs) {collection Al = new arraylist (); reflectpoint rp1 = new reflectpoint (3, 3 ); reflectpoint RP2 = new reflectpoint (5, 6); reflectpoint RP3 = new reflectpoint (3, 3); Al. add (rp1); Al. add (RP2); Al. add (RP3); Al. add (rp1); system. out. println ("list:" + Al. size (); // list: 4 collection HS = new hashset (); HS. add (rp1); HS. add (RP2); HS. add (RP3); HS. add (rp1); // overwrites the hashcode method and equ ALS method. RP1 is added repeatedly. Only one RP1 is added. RP1 and RP3 are also added. rp3system is not added. out. println ("HS:" + HS. size (); // HS: 2 [RP1 and RP2 in the Set memory] system. out. println (HS); // [3 3, 5 6] // After the element RP1 is added to the set, modify the member variable value of the object RP1, this member variable is involved in the calculation of the hashcode () value. The RP1 removal operation rp1.x = 100; HS. remove (rp1); // remove element // two elements are found. The remove method cannot remove the original RP1 object because the hash value is modified, causing memory leakage !! System. Out. println (HS );}}