存储自定义对象,并保证元素的唯一性
如果两个对象的成员变量值都相同,则为同一个元素
import java.util.HashSet;
public class HashSetDemo2 {
public static void main(String[] args) {
HashSet<Student> hs = new HashSet<Student>();
// 创建学生对象
Student s1 = new Student("孙悟空", 30);
Student s2 = new Student("唐僧", 20);
Student s3 = new Student("猪八戒", 30);
Student s4 = new Student("沙和尚", 40);
Student s5 = new Student("孙悟空", 30);
Student s6 = new Student("孙悟空", 60);
// 把学生添加到集合
hs.add(s1);
hs.add(s2);
hs.add(s3);
hs.add(s4);
hs.add(s5);
hs.add(s6);
for (Student s : hs) {
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
publ