您的位置:首页 > 其它

关于hashCode 分析还有有序集合与无序集合的存取条件,避免造成内容泄露

2012-03-18 14:06 316 查看
package AdvanceJava;

import static java.lang.System.out;

import java.util.Collection;

import java.util.Comparator;

import java.util.HashSet;

import java.util.TreeSet;

class My implements Comparator

{

@Override

public int compare(Object o1, Object o2) {

// TODO Auto-generated method stub

return 0;

}

}

class Person_Hash implements Comparable

{

public String name;

public int age;

public Person_Hash(String name,int age)

{

this.name = name;

this.age = age;

}

public boolean equals(Object obj)

{

Person_Hash p = (Person_Hash)obj;

if(obj==null || !(p instanceof Person_Hash))

return false;

if(p.name.equals(this.name)&&(p.age == this.age))

return true;

else

return false;

}

public int hashCode()

{

return name.hashCode()+age*9;

}

public int compareTo(Object o) {

return 1;

}

}

/*

* 对于 存入到 hash 表中的元素(HashSet HashMap)如果存入后

* 就不要再改变有可以影响hashCode 结果的成员的值,

* 如果你在存入后改变了它的该对象的HashCode 的值,那么

* 该对象则不是你已经存入的那个,所以那个对象则不会再被使用,

* 日积月累,造成内在的泄露

*

*

*/

public class HashCodeTest {

public static void main(String args[])

{

Collection col = new HashSet();

Person_Hash p1 = new Person_Hash("boy",22);

Person_Hash p2 = new Person_Hash("boy",22);

Person_Hash p3 = new Person_Hash("boy",22);

Person_Hash p4 = new Person_Hash("boy",22);

col.add(p1);

col.add(p2);

col.add(p3);

col.add(p4);

out.println(col.size()); //输出结果为1,对于set 集合,其存取的条件在于hashcode 与 equals 两个方法的

//的返回值,在源代码里有这样一个条件

// e.hash == hash &&(e.key == k || key.equals(e.key))

//trytree();

memeryOut();

}

public static void trytree()

{

Collection col = new TreeSet();

Person_Hash p1 = new Person_Hash("boy",22);

Person_Hash p2 = new Person_Hash("boy",22);

Person_Hash p3 = new Person_Hash("boy",22);

Person_Hash p4 = new Person_Hash("boy",22);

col.add(p1);

col.add(p2);

col.add(p3);

col.add(p4);

out.println(col.size()); //其结果为4.因为它们的comparator 一直相等,所以都被存入进集合

// 可知,对于 有序集合来说,其存取的责任都落在了comparator 上,无论hashcode

//与equals 是否相等,只要comparator 返回不等于0,那它都将会被存入集合

}

public static void memeryOut()

{

Collection set = new HashSet();

Person_Hash p1 = new Person_Hash("boy",22);

Person_Hash p2 = new Person_Hash("girl",21);

Person_Hash p3 = new Person_Hash("person",222);

set.add(p1);

set.add(p2);

set.add(p3);

out.println(set.size());// 现在的结果是3

p1.name = "dog";

set.remove(p1);

out.println(set.size());// 现在的结果然后是3,因为我们在前面改变了p1的name.也就是间接改变了hashcode值

// 而hash 在取值的时候,依靠的就是hashcode,而我们改变了它的hashcode ,所以也就找不到了

//修改生的 p1 对象,所以:

// 我们对已经存入set 集合中的对象不要再修改其影响hashcode 计算的属性,不然会

//造成内在泄露,这个很重要,而且不容易检查出来

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: