1 package day6.lesson1;
2
3 import java.util.HashSet;
4
5 /*
6 1.6 案例-HashSet集合存储学生对象并遍历
7
8 创建一个存储学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合
9 要求:学生对象的成员变量值相同,我们就认为是同一个对象
10
11 */
12 public class HashSetDemo4 {
13 public static void main(String[] args) {
14 HashSet<Student> hs = new HashSet<>();
15
16 Student s1 = new Student("tom", 22);
17 Student s2 = new Student("sam", 23);
18 Student s3 = new Student("amy", 21);
19 Student s4 = new Student("amy", 21);
20
21 hs.add(s1);
22 hs.add(s2);
23 hs.add(s3);
24 hs.add(s4);
25
26 for (Student s: hs){
27 System.out.println(s.getName() + "," + s.getAge());
28 }
29 /*
30 Student类重写equals()和hashCode()之前输出:
31 sam,23
32 amy,21
33 tom,22
34 amy,21
35
36 为保证元素唯一性,Student类重写equals()和hashCode()两个方法(alt+insert自动生成)
37
38 Student类重写equals()和hashCode()之后输出:
39 tom,22
40 amy,21
41 sam,23amy,21
42 sam,23
43 */
44 }
45 }
1 package day6.lesson1;
2
3 public class Student {
4
5 private String name;
6 private int age;
7
8 public Student() {
9 }
10
11 public Student(String name, int age) {
12 this.name = name;
13 this.age = age;
14 }
15
16 public void setName(String name) {
17 this.name = name;
18 }
19
20 public void setAge(int age) {
21 this.age = age;
22 }
23
24 public String getName() {
25 return name;
26 }
27
28 public int getAge() {
29 return age;
30 }
31
32 //HashDemo2.java
33 /*@Override
34 public int hashCode() {
35 // return super.hashCode(); //默认
36 return 0; //此时可以实现让不同对象的哈希值相同
37 }*/
38
39 //HashSetDemo4.java
40 @Override
41 public boolean equals(Object o) {
42 if (this == o) return true;
43 if (o == null || getClass() != o.getClass()) return false;
44
45 Student student = (Student) o;
46
47 if (age != student.age) return false;
48 return name != null ? name.equals(student.name) : student.name == null;
49 }
50
51 @Override
52 public int hashCode() {
53 int result = name != null ? name.hashCode() : 0;
54 result = 31 * result + age;
55 return result;
56 }
57 }