`
潇洒的拖鞋
  • 浏览: 9509 次
  • 性别: Icon_minigender_1
最近访客 更多访客>>
社区版块
存档分类
最新评论

黑马程序员-------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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics