java中WeakHashMap的个人理解

在读了很多关于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;
	}
	@Override
	public 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>();
		// 初始化一个学生类s1
		Student 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 block
			e.printStackTrace();
		}
		System.out.println(whm);// 再打印看现在的结果
		// {Student [name=a, no=1]=1}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值