- package Container;
- import java.util.HashSet;
- import java.util.Iterator;
- /*
- |--Set:元素无序,且不能重复。
- |--HashSet:底层结构是哈希表。
- |--TreeSet:
- Set集合的功能和Collection是一致的。
- */
- class Person1//定义人对象
- {
- private String name;
- private int age;
-
- Person1(String name, int age)
- {
- this.name = name;
- this.age = age;
- }
-
- public boolean equals(Object obj)//重写equals方法。
- {
- if(!(obj instanceof Person))
- return false;
-
- Person1 p = (Person1)obj;
- System.out.println(this.name+"----vs----"+p.name);
- return this.name.equals(p.name)&&this.age==p.age;
-
- }
-
- public int hashCode()//覆盖hashCode重新计算哈希值
- {
- System.out.println("wo lai jisuan hash!!");
- return 60;
- }
-
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
- public class HashSetDemo {
-
- public static void sop(Object obj)//打印
- {
- System.out.println(obj);
- }
- public static void main(String[] args) {
- HashSet<Person1> hs = new HashSet<>();
-
- hs.add(new Person1("lisa01",21));
- hs.add(new Person1("lisa02",21));
- hs.add(new Person1("lisa03",21));
- hs.add(new Person1("lisa04",21));
-
- for(Iterator<Person1>it = hs.iterator();it.hasNext();)
- {
- Person1 p = it.next();
- sop(p.getName()+"--------"+p.getAge());
- }
- }
- }
复制代码 |
|