import java.util.*;
class HashSetLianXi
{
public static void main(String[] args)
{
//创建集合存储对象
HashSet hs= new HashSet();
hs.add(new People("张三",10));
hs.add(new People("历史",20));
hs.add(new People("王五",30));
hs.add(new People("张三",10));
//创建集合的迭代器,取出集合元素
Iterator it=hs.iterator();
while(it.hasNext())
{
People p=(People)it.next();//强转,因为add添加的是Object对象,不能使用子类特有功能
System.out.println(p.getName()+"....."+p.getAge());
}
}
}
//描述对象
class People
{
private String name;
private int age;
People(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
//复写 hashCode(),建立对象自己的哈希值
public int hashCode()
{
return name.hashCode()+age;
}
//复写 equals()。若是哈希值相等,继续按此方式比较
public boolean equals(Object obj)
{
if(!(obj instanceof People))
return false;
People p=(People)obj;
return this.name.equals(p.name)&& this.age==p.age;
}
}
HashSet底层是哈希表,不能排序 , 判断重复依据hashCode(),若相等,继续判断equals(),但不能排序
学习之后,自己敲代码练习
|