黑马软件工程师-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.****.net/heima