日期:2014-05-20 浏览次数:20927 次
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.lang.ref.*;
public class Name{
private String firstName;
private String lastName;
private static final Set<SoftReference<Name>> names=
new HashSet<SoftReference<Name>>();
public Name(String firstName,String lastName){
this.firstName=firstName;
this.lastName=lastName;
}
public static Name valueOf(String firstName,String lastName){
Iterator<SoftReference<Name>> it=names.iterator();
while(it.hasNext()){
SoftReference<Name> ref = it.next();
Name name = ref.get();
if(name!=null
&& name.firstName.equals(firstName)
&& name.lastName.equals(lastName)){
return name;
}
}
Name name = new Name(firstName,lastName);
names.add(new SoftReference<Name>(name));
return name;
}
public static void main(String[] args){
Name n1=Name.valueOf("Xiaohong","Wang");
Name n2=Name.valueOf("Xiaohong","Wang");
Name n3=Name.valueOf("Xiaodong","Zhang");
System.out.println(n1);
System.out.println(n2);
System.out.println(n3);
System.out.println(n1==n2);
}