不可以改变对象之缓存

3/8/2017来源:ASP.NET技巧人气:1909

public class Name{ PRivate String firstName; private String lastName; private static final Set<SoftReference<Name>>names=new HashSet<SoftReference<Name>>(); public static Name valueOf(String firstName,String lastName){ for(SoftReference<Name>ref:names){ Name name=ref.get(); if(name!=null&&name.getFirstName().equals(firstName)&&name.getLastName().equals(lastName)){ return name; } } Name name=new Name(firstName, lastName); SoftReference<Name>softReference=new SoftReference<Name>(name); names.add(softReference); return name; } private Name(String firstName,String lastName){ this.firstName=firstName; this.lastName=lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } }

这里用到了SoftReference 是指的是弱引用,他可以在内存不足的时候实现自动释放