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: