import java.util.*;
class Demo
{
public static void main(String[] args)
{
HashSet<Person> hs=new HashSet<Person>();
Person p1=Person.newPerson("zhangsan01",20);
Person p2=Person.newPerson("zhangsan01",20);//传入的对象相同了,被覆盖了
Person p3=Person.newPerson("zhangsan04",20);
Person p4=Person.newPerson("zhangsan03",25);
hs.add(p1);
hs.add(p2);
hs.add(p3);
hs.add(p4);
Iterator<Person> it=hs.iterator();
while (it.hasNext())
{
Person p=it.next();
System.out.println(p.getName()+"::"+p.getAge());
}
}
}
class Person
{
private String name;
private int age;
//创建对象池 用于存储Person对象
private static HashSet<Person> objectPool=new HashSet<Person>();
public Person(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
//定义方法,用于创建Person对象
public static Person newPerson(String name,int age)
{
for (Person p:objectPool )
{
//如果对象已经在对象池中存在,则直接返回该对象
if(p.name.equals(name)&&p.age==age)
return p;
}
//如果该对象不存在,则创建新对象,并将该对象添加到对象池中
Person p=new Person(name,age);
objectPool.add(p);
return p;
}
}作者: 孟浩然 时间: 2012-6-26 21:27
耿鑫 发表于 2012-6-26 17:42
Person p1=Person.newPerson("zhangsan01",20);在对象池里有这个对象了,第二次Person p2=Person.newPerson ...