- import java.util.HashSet;
- import java.util.Iterator;
- /*HashSet是如何保证数据唯一性?
- 是通过元素的两个方法,hashCode和equals来完成。
- 如果元素的hashCode值相同,才会判断equals是否为true.
- 如果元素的hashCode值不同,不会调用equals.*/
- public class HashSetDemo {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- HashSet<Person> hs=new HashSet<Person>();
-
- hs.add(new Person("al",11));
- hs.add(new Person("a2",12));
- hs.add(new Person("a2",12));
- hs.add(new Person("a3",13));
- hs.add(new Person("a3",13));
- hs.add(new Person("a4",14));
-
- Iterator<Person> it=hs.iterator();
- while(it.hasNext()){
- Person p=it.next();
- sop(p.getName()+"..."+p.getAge());
- }
- }
-
-
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
- class Person{
-
- private String name;
- private int age;
- public Person(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;
- }
- @Override
- public boolean equals(Object arg0) {
- // TODO Auto-generated method stub
- if(!(arg0 instanceof Person))
- return false;
- Person p=(Person)arg0;
- return this.name.equals(p.getName())&&this.age==p.getAge();
- }
- @Override
- public int hashCode() {
- // TODO Auto-generated method stub
- return this.name.hashCode()+this.age*12;
- }
-
-
- }
复制代码
|