Memory leakage caused by Hashset of HashCode in Java

Source: Internet
Author: User


Memory leakage is a piece of memory occupied by an object. When this object is not used, the memory has not been withdrawn.

 

Example

Package cn. xy. test;

Public class Point2
{
Private int x;
Private int y;

Public Point2 (int x, int y)
{
Super ();
This. x = x;
This. y = y;
}

@ Override
Public int hashCode ()
{
Final int prime = 31;
Int result = 1;
Result = prime * result + x;
Result = prime * result + y;
Return result;
}

@ Override
Public boolean equals (Object obj)
{
If (this = obj) return true;
If (obj = null) return false;
If (getClass ()! = Obj. getClass () return false;
Point2 other = (Point2) obj;
If (x! = Other. x) return false;
If (y! = Other. y) return false;
Return true;
}

Public int getX ()
{
Return x;
}

Public void setX (int x)
{
This. x = x;
}

Public int getY ()
{
Return y;
}

Public void setY (int y)
{
This. y = y;
}

}

Public class HashSetAndHashCode2
{
Public static void main (String [] args)
{
HashSet <Point2> hs2 = new HashSet <Point2> ();
Point2 p21 = new Point2 (3, 3 );
Point2 p22 = new Point2 (3, 5 );
Hs2.add (p21 );
Hs2.add (p22 );
P22.setY (7 );
Hs2.remove (p22 );
System. out. println (hs2.size ());
}
}

Many people think that the printed result is 1. The result is 2. Why? After an object is stored in a Hashset, If you modify the fields involved in Calculation of hashcode, the value of the modified hashcode is different from the value of the originally stored hashcode, in this way, the contains element cannot be found through hashcode, so it cannot be deleted. This tells us that when an object is stored in a Hashset, do not modify the fields related to the calculation of hashcode.

 

 

Share:

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.