JavaSE-15.1.4【案例-HashSet集合存储学生对象并遍历】

复制代码
 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 }
复制代码

 

posted @   yub4by  阅读(128)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示