即讨论hash算法的优点
1、存储的集合是hash集合,对象的hash码才有用,也就是类的hashCode()才起作用
2、Object中定义了一个hashCode()方法,用来返回每个Java对象的hash码,然后根据得到的hash码将对象存放到相应的区域。
3、已存入hash集合的元素,不能再修改该元素那些参与hash运算的字段值,否则,造成内存泄漏。
4、hash算法将hash集合分成若干不同的区域,若存在两个hash码相同的对象,这两个对象将存放在不同的区域
5、使用hash能够快速查找
6、obj1.equals(obj2) == ture,它们的hash码一定相同,但hash码相同的两个对象,不一定是同一个对象。
class HashObject{
private int hashx, hashy, z;
public HashObject(int ax, int ay, int az){
hashx = ax;
hashy = ay;
z = az;
}
public void setHashx(int ax){hashx = ax;}
public void setZ(int az){z = az;}
/*右键-Source-generate hashCode() and equals()*/
public int hashCode(){
final int prime = 31;
int result = 1;
result = prime * result + hashx;
result = prime * reuslt + hashy;
return result;
}
}
//main
Collection collection = new HashSet();
HashObject hashObj1 = new HashObject(1,2,3);
HashObject hashObj2 = new HashObject(2,3,4);
HashObject hashObj3 = new HashObject(3,4,5);
HashObject hashObj4 = new HashObject(1,2,3);
collection.add(hashObj1);
collection.add(hashObj2);
collection.add(hashObj3);
collection.add(hashObj4);
collection.remove(j4); //Success
System.out.println(collention.size()); //output: 3
hashObj1.setHashX(3);
collection.remove(j1); //Fail,内存泄漏
System.out.println(collention.size()); //output: 3
技术要点:1、使用反射和配置文件优化上面的代码Collection collection = new HashSet();
//main
InputStream ips = new FileInputStream("config.progerties"); //config.progerties存在一行配置信息:className=java.util.HashSet
Properties props = new Properties();
props.load(ips);
ips.close();
String className = props.getProperty("className");
Collection collection = (Collection)Class.forName(className).newInstance();
HashObject hashObj1 = new HashObject(1,2,3);
HashObject hashObj2 = new HashObject(2,3,4);
HashObject hashObj3 = new HashObject(3,4,5);
HashObject hashObj4 = new HashObject(1,2,3);
collection.add(hashObj1);
collection.add(hashObj2);
collection.add(hashObj3);
collection.add(hashObj4);
JAVA中存在内存泄漏码?为什么? |
|