HashSet

HashSet的底层数据结结构是哈希表,哈希表用于存储哈希值,

    hashSet中比较对象是否一样的是自动调用对象的hashCode和equals方法(hash值是操作系统给的,equals是Object继承的。自己也可以重写),当hash值相同时才调用equals,否则不要调用,只有当hashcode与equals值都相等是才视为同一对象。String类重新了equals方法。所以一般用hashSet时,要对类重写hashCode 和equals方法。

/

未重写时比较的是地址==。内容一样也会存进去

/

public class HashSetTest {

public static void main(String[] args) {
// TODO Auto-generated method stub
Set s = new HashSet();
s.add(new Person5("xiaoli",23));
s.add(new Person5("xiaoli",23));
s.add(new Person5("xiaoli",23));
s.add(new Person5("xiaoli",23));
Iterator it = s.iterator();
while(it.hasNext()){
Person5 p1 =(Person5)it.next();
System.out.println(p1.getName()+"----"+p1.getAge());
}
}

}

class Person5 {
private String name;
private int 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;
}
public Person5(String name, int age) {
super();
this.name = name;
this.age = age;
}

}

结果是:

xiaoli----23
xiaoli----23
xiaoli----23
xiaoli----23

/**

重写hashCode和equals后:

**/


public class HashSetTest {

public static void main(String[] args) {
// TODO Auto-generated method stub
Set s = new HashSet();
s.add(new Person5("xiaoli",23));
s.add(new Person5("xiaoli",23));
s.add(new Person5("xiaoli",23));
s.add(new Person5("xiaoli",23));
Iterator it = s.iterator();
while(it.hasNext()){
Person5 p1 =(Person5)it.next();
System.out.println(p1.getName()+"----"+p1.getAge());
}
}

}

class Person5 {
private String name;
private int 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;
}
public Person5(String name, int age) {
super();
this.name = name;
this.age = age;
}

public int hashCode(){
return this.age;

}

public boolean equals(Object o){
Person5 p =(Person5)o;
if(!(p instanceof Person5))
return false;
return this.name.equals(p.name);
}

}

结果是:

xiaoli----23

 

posted on 2015-06-19 11:15  卖肾割阑尾  阅读(163)  评论(0)    收藏  举报

导航