本帖最后由 郑庆伟 于 2012-7-8 20:13 编辑
import java.util.*;
class HashSetTest
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
HashSet hs = new HashSet();
hs.add(new Person("a1",11));
hs.add(new Person("a2",12));
hs.add(new Person("a3",13));
hs.add(new Person("a4",14));
sop(hs.remove(new Person("a3",13)));
Iterator it = hs.iterator();
while(it.hasNext())
{
Person p = (Person)it.next();//这里是向下转型是吧,为什么要要这么做呢。是多态吧,父类引用指向子类对象?
sop(p.getName()+"::"+p.getAge());
}
}
}
class Person
{
private String name;
private int age;
Person(String name, int age)
{
this.name = name;
this.age = age;
}
public int hashCode()
{
System.out.println(this.name+".....hashCode()");
return 60;//name.hashCode()+age;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
return false;
Person p = (Person)obj;
System.out.println(this.name+"..equals.."+p.age);
return this.name.equals(p.name) && this.age == p.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
} |
|