import java.util.*;
public class CollcetionTest {
public static void main(String[] args)
{
HashSet<People> hs = new HashSet<People>();
hs.add(new People("zhangsan001",21));
hs.add(new People("zhangsan02",20));
hs.add(new People("zhangsan003",23));
hs.add(new People("zhangsan",23));
hs.add(new People("zhangsan",23));
for (Iterator<People> it = hs.iterator();it.hasNext() ; )
{
People p =it.next();
System.out.println(p.getName()+"..."+p.getAge());
}
HashSet<String> hs1 = new HashSet<String>();
hs1.add("abc01");
hs1.add("abc03");
hs1.add("abc02");
hs1.add("abc03");
printCollection(hs1);
}
public static void printCollection(HashSet<?> hs1)
{
for (Iterator<?> it = hs1.iterator();it.hasNext() ; )
{
System.out.println(it.next());
}
}
}
class People<P extends People>
{
private String name;
private int age;
People(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
//覆写hashCode方法比较
public int hashCode()
{
return name.hashCode()+age*39;
}
public boolean equals(P p1)
{
//if(!(obj instanceof People))
//return false;
//People p = (People)obj;
//System.out.println(this.name+".....equals"+p.name);
return this.name.equals(p1.name)&&this.age==p1.age;
}
}
泛型自定义对象的equlas怎么写?求高手!...怎么写都运行equals方法。。郁闷
|