---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------
当hashSet里面存储很多元素的时候如果你想查找某个元素就要通过hashCold算法取得hash值,因为hashSet通过hashcold算法分为了若干个区域,在存储对象时候,先通过hashcold算法来决定该对象存储在那个区域,查找hashSet里面对象时,先通过hashcold算法拿到hashcold值在到hashSet对应的区域查找。
容易造成的内存泄露:
如果对象已经存入了hashSet那么就不能去修改该对象的值,因为修改了值过后hash值也就改变了,存储的地方随之发生改变,当你再去remove该对象的时候已经不再原来的区域,所以无法remove掉该对象,如果你在不断地存储对象也在不断地修改值,时间长了就会造成内存泄露代码如下:
public class ReflectPoint {
private int x;
public int y;
public String a="abcderb";
public String b="bbkdbshbb";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
return a+"-----"+b;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
public class HashSet_HashCold {
public static void main(String[] args) throws Exception{
Collection set = new HashSet();
ReflectPoint r1 = new ReflectPoint(3, 3);
ReflectPoint r2 = new ReflectPoint(4, 5);
ReflectPoint r3 = new ReflectPoint(3, 3);
ReflectPoint r4 = new ReflectPoint(7, 8);
set.add(r1);
set.add(r2);
set.add(r3);
set.add(r4);
set.add(r1); //存储同一个对象hashe值相等所以存不进去
//内存泄露问题
r1.y=8;
set.remove(r1);
System.out.println(set.size());
}
}
---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------