运用HashSet存储自定义对象
——Person必须重写HashCode()方法和equal()方法
public class Person {
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 Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
//Person必须重写HashCode()方法和equal()方法
@Override
public int hashCode() {
System.out.println("Person.hashCode()");
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
System.out.println("Person.equals()");
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
public class TestHashSet {
public static void main(String[] args) {
//HashSet底层数据结构使用的是哈希表,主结构是数组 +链表
HashSet hs = new HashSet();
hs.add("word");
Person p1 = new Person("张三",25);
Person p2 = new Person("李四",25);
Person p3 = new Person("王二麻子",25);
Person p4 = new Person("张三",25);
hs.add(p1);
hs.add(p2);
hs.add(p3);
hs.add(p4);
Iterator it = hs.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}