黑马程序员——hashCode方法解决内存泄露

来源:互联网 发布:城市与文明游戏 知乎 编辑:程序博客网 时间:2024/04/30 13:35

---------------------- android培训、java培训、期待与您交流! ----------------------

 

hashCode方法与HashSet类

例:

目的:解决内存泄露

public class ReflectPoint{
 private int x;
 public int y;
 public ReflectPoint(int x,int y){
  super();
  this.x=x;
  this.y=y;

  //建立Hashcode,重写equals方法:右键-->Source-->Generate hashCode() and equals()   
  
 }
}

public class ReflectTest{
 public static void main(String[] args){
  //父类接口
  Collection collections= new ArrayList();// 值:4
  //Collection collections= new HashSet();// 值:3 未用Hashcode,重写equals方法
  ReflectPoint pt1 = new ReflectPoint(3,3);
  ReflectPoint pt2 = new ReflectPoint(5,5);
  ReflectPoint pt3 = new ReflectPoint(3,3);
  collections.add(pt1);
  collections.add(pt2);
  collections.add(pt3);
  collections.add(pt1);// HashSet集合里有相同的Hashcode值,会替换掉。
  
  System.out.println(pt3.equals(pt1));
  //false  比较的是Hashcode值,只有通过hashCode重写equals方法,值才能为 "true",值为:2
  System.out.println(collections.size());
 }
}

 

把hash集合里每个对象换算成hash值,通过hash值分成若干个区域,然后比较hash值在哪个区域,对这个区域里hash值,逐个进行比较,判断是否相等。只有规定存储集合是Hash算法这种类型的集合,hashCode值才有价值。

提示:

当一个对象被存储进HashSet集合中以后,就不能修改这个对象中的那些参与计算哈希值的字段了,否则,对象修改后的哈希值与最初存储进HashSet集合中时的哈希值就不同了,在这种情况下,即使在contains方法使用该对象的当前引用作为的参数去HashSet集合中检索对象,也将返回找不到对象的结果,这也会导致无法从HashSet集合中单独删除当前对象,从而造成内存泄露。

例:

//pt1.y = 7;    // 值为:1
pt1.y = 7;      // 值为:2 造成内存泄露                   
collections.remove(pt1);
System.out.println(collections.size());


 

---------------------- android培训、java培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net/heima

原创粉丝点击