在HashSet集合中 ,Person去重是依据复写equals和hashcode这个两个方法 具体为啥依据这两个方法还是有点不清!!!
只知道如果不复写的话HashSet就看的是Person这个对象的地址值!!!
迷迷糊糊的根据毕老师老师讲的写了一段代码 。可是还是去不了重 大家帮忙看看
- import java.util.*;
- class HashSetDemo
- {
- public static void main(String[] args)
- {
- HashSet<Person> hs = new HashSet<Person>();
- hs.add(new Person("zhangsan",21));
- hs.add(new Person("lisi",20));
- hs.add(new Person("lisi",20));
- hs.add(new Person("wangwu",24));
- hs.add(new Person("zhaoliu",23));
- hs.add(new Person("zhaoliu",23));
-
- Iterator <Person>it = hs.iterator();
- while(it.hasNext())
- {
- Person p = it.next();
- System.out.println(p);
- }
- }
- }
- class Person
- {
- private String name;
- private int age;
- Person(String name,int age){
- this.name = name;
- this.age = age;
- }
- public String toString()
- {
- return name+"..."+age;
- }
- public String getName(){return name;}
- public int getAge(){return age;}
- public int hashcode()
- {
- final int x = 5;
- return this.name.hashCode() + this.age * x;
- }
- public boolean equals(Object obj)
- {
- if (this == obj)
- return true;
- if (obj instanceof Person)
- { Person p = (Person)obj;
- return this.name.equals(p.name) && this.age == p.age;}
- return false;
-
-
- }
- }
复制代码
|