package com.tercher.demo; import java.util.HashSet; import java.util.Iterator; public class HashSetDemo { public static void main(String[] args) { /* * HashSet存放散列,当存储对象是: * 先生成哈希码,调用方法:hashCode() * 如果哈希码相同,则调用添加对象的equals()方法,对两个对象进行比较 * 默认的比较是比较对象的地址,对象的地址不同则可以添加 * 例:Student st = new Student("xiaowang1", 24); * hs.add(st); * hs.add(st);此时值能添加一个 * 说明:HashSet集合在调用add()方法时会自动的调用hashCode()和对象的equals() * 若对象没有重写equals()方法,则调用的默认的Object类中的方法(比较地址) * * 需求:使得两个对象只要属性值全相同,即设定为同一元素,则不能存放 * * 步骤:1,建立新的HashSet集合,存放不能重复的元素 * 2,重写Student类的HashCode()方法和equals()方法 * 3,添加元素时的比较 * 4,输出新集合的不重复元素的集合 */ HashSet<Student> hs = new HashSet<Student>(); hs.add(new Student("xiaowang", 20)); hs.add(new Student("xiaowang1", 24)); hs.add(new Student("xiaowang1", 24)); hs.add(new Student("xiaowang2", 22)); hs.add(new Student("xiaowang3", 26)); Iterator<Student> iter = hs.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } Student st = new Student("xiaowang1", 24); HashSet<Student> newhs = new HashSet<Student>(); newhs.add(st); newhs.add(st); newhs.add(new Student("xiaowang", 20)); newhs.add(new Student("xiaowang1", 24)); newhs.add(new Student("xiaowang1", 24)); newhs.add(new Student("xiaowang2", 22)); newhs.add(new Student("xiaowang3", 26)); System.out.println("重写后的HashSet:"); Iterator<Student> it = newhs.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } class Student{ private String name; private int age; public Student(){ } public Student(String name,int age){ this.name = name; this.age = age; } @Override public String toString() { return this.name+"-----"+this.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; } /* * 重写对象的两个方法() * name.hashCode() 调用的是String类中的hashCode()方法, * 比较的是字符串相同即为同一个哈希码 */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; System.out.println(this.getClass().getName()+":"+name.hashCode());//当前对象的名字哈希码 result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (!( obj instanceof Student)) { return false;//判断对象类型是否一样 } Student stu = (Student) obj; System.out.println("比较的两个对象的name值:"+this.name+"---"+stu.name); return this.name.equals(stu.name) && (this.age == stu.age); } }