关于反射自建框架 HashCode 【内存泄露】问题简析

来源:互联网 发布:淘宝客服的简历 编辑:程序博客网 时间:2024/05/06 12:13

1.从涉及反射的知识点开始 ,由 HashCode 分析出的内存泄露问题:


对于利用发射来构建框架 , 利用 HashCode 的例子来说明内存泄露的原因跟问题(面试题详见V_26):

-----------------------------Class_ReflectPoint:

public int x;
private int y;
public String a1="aabaa";
public String a2="aabaa";
public String a3="aabaa";

//定义 hashCode 方法 ,实现对 hashCode 的改变 ,用来模拟内存泄露
public int hashCode()
{
final int prime=30;
int result=1;
result=prime*result+x;
result=prime*result+y;
return result;
}

-----------------------------Class_Reflect_2:

public static void main(String[] args) 
{
        Collection  collection1=new HashSet();    //打印结果为:3因为Set不可以重复存入pt1
        Collection  collection2=new ArrayList();  //打印结果为:4因为List 可以重复存入pt1 


            //collection1.add(new ReflectPoint(3,3));
   ReflectPoint pt1=new ReflectPoint(3,3);
   ReflectPoint pt2=new ReflectPoint(3,5);
   ReflectPoint pt3=new ReflectPoint(2,2);
   
   collection1.add(pt1);
   collection1.add(pt2);
   collection1.add(pt3);
   collection1.add(pt1);
   
   pt1.x=7;  //修改 pt1的 hashCode值 ,修改后无法删除pt1 ,结果为:3个
   collection1.remove(pt1);  //修改了 pt1的 hashCode值 ,那么删除的就再不是原来的 pt1 ,造成了内存泄露
   System.out.println(collection1.size());
   System.out.println(collection2.size());
   
}

-----------------------------以上例子可以用来在【面试题】中运用

如:(1)谈谈 HashCode 的方法和运用   (2)请例举几个java中的内存泄露问题