黑马程序员-------hash改变造成的内存泄露

---------------------- android培训java培训、期待与您交流! ----------------------
  String className = props.getProperty("classMame");
        Collection collections = (Collection)Class.forName(className).newInstance();//运用config配置文件和反射进行实例collection
       
//      Collection collections = new HashSet() ;
        ReflectPoint pt1 = new ReflectPoint(3,3);
        ReflectPoint pt2 = new ReflectPoint(3,5);
        ReflectPoint pt3 = new ReflectPoint(3,3);
       
        collections.add(pt1);
        collections.add(pt2);
        collections.add(pt3);
       
        pt1.y = 7;//使用HashSet(与hash值相关的类)时,在保存后不能修改参与hash值计算的参数,不然会导致对象不能删除,造成内存泄漏!
        collections.remove(pt1);
       
        System.out.println(collections.size());
  这里打印出来的长度还是3;因为在删除对象前,修改了参与哈希值计算的属性值,导致jvm没有找到pt1对象的哈希值从而没有删除pt1对象!!

package HEIMA_refelct;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Properties;




public class ReflectTest1 {
    public static void main(String args[]) throws Exception{
        InputStream ips = new FileInputStream("config.properties");//[读取配置文件需根据文件路径输入相应路径(前面的写法是当config与工程平级)]
//        InputStream ips = ReflectTest1.class.getResourceAsStream("resource/config.properties");//运用字节码的方法取得输入流
        Properties props = new Properties();
        props.load(ips);
        ips.close();
        String className = props.getProperty("classMame");
        Collection collections = (Collection)Class.forName(className).newInstance();//运用config配置文件和反射进行实例collection
        
//        Collection collections = new HashSet() ;
        ReflectPoint pt1 = new ReflectPoint(3,3);
        ReflectPoint pt2 = new ReflectPoint(3,5);
        ReflectPoint pt3 = new ReflectPoint(3,3);
        
        collections.add(pt1);
        collections.add(pt2);
        collections.add(pt3);
        
        pt1.y = 7;//使用HashSet(与hash值相关的类)时,在保存后不能修改参与hash值计算的参数,不然会导致对象不能删除,造成内存泄漏!
        collections.remove(pt1);
        
        System.out.println(collections.size());
    }

}

 

---------------------- android培训java培训、期待与您交流! ----------------------
详细请查看:http://edu.csdn.net/heima

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值