java中WeakHashMap的个人理解

来源:互联网 发布:excel怎么汇总数据 编辑:程序博客网 时间:2024/06/01 14:44

在读了很多关于WeakHashMap的文章后 决定自己实践下 加深对WeakHashMap的理解


首先贴上去代码 创建个学生类测试用

public class Student{private String name;private String no;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getNo() {return no;}public void setNo(String no) {this.no = no;}public Student(String name,String no){this.name = name;this.no = no;}@Overridepublic String toString() {return "Student [name=" + name + ", no=" + no + "]";}}
然后贴上去测试代码

public class Test {public static void main(String[] args) {// 创建WeakHashMap对象// WeakHasmMap是弱引用,当Key中没有对象的引用时 WeakHashMap就会自动删除这个key的entry// 个人理解 WeakHashMap 可以当做缓存去用Map<Student, Integer> whm = new WeakHashMap<Student, Integer>();// 初始化一个学生类s1Student s1 = new Student("a", "1");// put put put进去whm.put(s1, 1);whm.put(new Student("b", "2"), 2);whm.put(new Student("c", "3"), 3);// 看看现在的map中的结果System.out.println(whm);// {Student [name=a, no=1]=1, Student [name=b, no=2]=2, Student [name=c,// no=3]=3}// 调用gc去回收下垃圾System.gc();try {Thread.sleep(3000);// 让给gc回收垃圾} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(whm);// 再打印看现在的结果// {Student [name=a, no=1]=1}}}



0 0