本帖最后由 帅气的冬瓜 于 2013-11-22 12:15 编辑
package Collections;
import java.util.HashSet;
import java.util.Iterator;
public class HashSetDemo {
/**
*
* HashSet保证元素唯一,通过hashcode和equals来完成
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet hs=new HashSet();
hs.add(new Person1("wangwu",23));
hs.add(new Person1("lisi",33));
hs.add(new Person1("zhangsan",20));
hs.add(new Person1("zhaoqian",20));
hs.add(new Person1("lisi",33));
Iterator it=hs.iterator();
while (it.hasNext()){
Person1 p=(Person1)it.next();
sop(p.getName()+"-----"+p.getAge());
}
}
public static void sop(Object obj){
System.out.println(obj);
}
}
class Person1{
private String name;
private int age;
Person1(String name,int age){
this.name=name;
this.age=age;
}
public int hashCode(){
System.out.println(this.name+".....hashCode()");
//return name.hashCode()+age*34;
return 60;
}
public boolean eauals(Object obj){
if (!(obj instanceof Person1))
return false;
Person1 p=(Person1)obj;
System.out.println(this.name+"....eauals....."+p.name);
return this.name.equals(p.name)&&this.age==p.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;
}
}
运行结果:
wangwu.....hashCode()
lisi.....hashCode()
zhangsan.....hashCode()
zhaoqian.....hashCode()
lisi.....hashCode()
lisi-----33
zhaoqian-----20
zhangsan-----20
lisi-----33
wangwu-----23 问题来了 :为什么重复元素没有去掉,很纳闷
|