Dark Horse Programmer------Java Reflection Learning Summary (II.)

Source: Internet
Author: User

----------------------------Java Training, Android training, look forward to communicating with you! -------------------------------

Comparison and hashcode analysis of Arraylist_hashset

Look at the following three pieces of code:

1. Define a Point class

1  PackageCom.itheima.day1;2 3  Public classReflectpoint {4     Private intx;5      Public inty;6     7      PublicReflectpoint (intXinty) {8         Super();9          This. x =x;Ten          This. y =y; One     } A}

2. Save several points to the code in the ArrayList collection:

1  Public classReflectTest6 {2 3      Public Static voidMain (string[] args) {4         //TODO auto-generated Method Stub5Collection CO =NewArrayList ();6         7Reflectpoint point1 =NewReflectpoint (3, 4); 8Reflectpoint Point2 =NewReflectpoint (5,8);9Reflectpoint Point3 =NewReflectpoint (3, 4);Ten          One Co.add (POINT3); A Co.add (point2); - Co.add (point1); - Co.add (POINT3); the          - System.out.println (Co.size ());//Results: 4 -  -     } +  -}

3. Save the same point to the code in the HashSet collection:

 PackageCom.itheima.day1;ImportJava.util.*; Public classReflectTest7 { Public Static voidMain (string[] args) {//TODO auto-generated Method StubCollection CO =NewHashSet (); Reflectpoint point1=NewReflectpoint (128, 128); Reflectpoint Point2=NewReflectpoint (5,8); Reflectpoint Point3=NewReflectpoint (128, 128);        Co.add (POINT3);        Co.add (Point2);        Co.add (POINT1);                Co.add (POINT3); System.out.println (Co.size ());//results: 3}

Analysis:

1, we all know that the elements in the HashSet collection cannot be duplicated.

2. As can be seen from the third code result 3, HashSet collection treats point1 and Point3 as two different points. The reason is because Point1 and Point3 's hashcode are different.

HashSet the method of determining whether the element is identical when adding elements:

1) First determine whether the hashcode of the element to be added is the same as the hashcode of the elements in the collection, and if not, the element is added directly to the collection;

2) If the hashcode is the same, it is judged by the Equals method of the element if there are duplicate elements.

3, and we generally think that if the coordinates of the two points are the same, we will consider them to be the same point.

This will let us rewrite the hashcode () and Equals () methods of the point class.

code example:

 PackageCom.itheima.day1; Public classReflectpoint {Private intx;  Public inty;  //Public String str1 = "Ball";    Public String str2 = "basketball"; Public String STR3 = "java";     PublicReflectpoint (intXinty) {        Super();  This. x =x;  This. y =y; }     Public intGetX () {returnx; }     Public voidSetX (intx) { This. x =x; }     Public intGetY () {returny; }     Public voidSety (inty) { This. y =y; } @Override PublicString toString () {returnstr1+ ":" +str2+ ":" +STR3; } @Override Public inthashcode () {Final intPrime = 31; intresult = 1; Result= Prime * result +x; Result= Prime * result +y; returnresult; } @Override Public Booleanequals (Object obj) {if( This==obj)return true; if(obj = =NULL)            return false; if(GetClass ()! =Obj.getclass ())return false; Reflectpoint Other=(reflectpoint) obj; if(X! =other.x)return false; if(Y! =other.y)return false; return true; }    }

Attention:

  When an object is stored in the HashSet collection, it is not possible to modify the fields in the object that are participating in the hash value, otherwise the hash value after the object has been modified is different from the hash value originally stored in the HashSet collection, in which case Even if the Contains method uses the object's current reference as a parameter to retrieve an object from the HashSet collection, the result of the object cannot be found, which also results in a memory leak because the current object cannot be deleted separately from the HashSet collection.

code example:

 PackageCom.itheima.day1;ImportJava.util.*; Public classReflectTest7 { Public Static voidMain (string[] args) {//TODO auto-generated Method StubCollection CO =NewHashSet (); Reflectpoint point1=NewReflectpoint (128, 128); Reflectpoint Point2=NewReflectpoint (5,8); Reflectpoint Point3=NewReflectpoint (128, 128);        Co.add (POINT3);        Co.add (Point2);        Co.add (POINT1);                Co.add (POINT3); Point3.sety (0);        Co.remove (POINT3); System.out.println (Co.size ());//The result is still 2}}

Note that this point3 hashcode has been changed so that the object is not retrieved in the collection, causing the deletion to fail and the object will persist, causing a memory leak.

  

Dark Horse Programmer------Java Reflection Learning Summary (II.)

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.