public class HashSetTest {
public static void main(String[] args) {
// 创建集合对象
HashSet<Student> studentHashSet = new HashSet<Student>();
// 创建学生对象
Student s1 = new Student("张三", 27);
Student s2 = new Student("李四", 22);
Student s3 = new Student("王五", 30);
Student s4 = new Student("张三", 27);
Student s5 = new Student("张三", 20);
Student s6 = new Student("何六", 22);
// 添加元素
studentHashSet.add(s1);
studentHashSet.add(s2);
studentHashSet.add(s3);
studentHashSet.add(s4);
studentHashSet.add(s5);
studentHashSet.add(s6);
// 遍历集合
for (Student s : studentHashSet) {
System.out.println(s.getName() + "---" + s.getAge());
}
}
static class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
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;
}
/**
* 重写equals方法
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
if (age != student.age) return false;
if (!name.equals(student.name)) return false;
return true;
}
/**
* 重写hashCode方法
* @return
*/
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}
}
}