import java.util.*;
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 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.name);
return this.name.equals(p.name)&&this.age==p.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class HashSetDemo1
{
public static void main(String[] args)
{
HashSet hs = new HashSet();
hs.add(new Person("a1",12));
hs = getHash(hs);
sop(hs);
sop("a1"+hs.contains(new Person("a1",12)));为什么这个SOP在迭代前是true,迭代回来后是false,不明
}
public static void sop(Object obj)
{
System.out.println(obj);
}
public static HashSet getHash(HashSet hs)
{
HashSet newHs = new HashSet();
Iterator it = hs.iterator();
while(it.hasNext())
{
Person p =(Person)it.next();
newHs.add(p.getName()+"::"+p.getAge());
}
return newHs;
}
}
|
|