有勇气的牛排博客
☰

Set 集合 Hash集合存储学生对象并遍历

有勇气的牛排 1944 Java 2021-08-20 00:54:01

知止自律打卡-微信小程序APP
一款微信自律打卡小程序,支持自定义打卡项目、习惯记录、项目日记、专注计时与数据统计。自律打卡、学习打卡、读书打卡、健身打卡、运动打卡、减肥打卡、戒色打卡、养生打卡、戒烟、戒酒、戒熬夜等多种场景。万能打卡模板自由创建。可自定义每日打卡目标,记录习惯连续天数,可视化追踪成长进度。
了解产品详情 →
微信搜索「知止自律打卡」
知止自律打卡微信小程序

1 Hash集合存储学生对象并遍历

需求:创建一个存储学生对象的集合,存储多个学生对象,使用程序实现在控制台遍历该集合

要求:学生对象的成员变量值相同,我们救人为是同一个对象

思路

1、定义学生类

2、创建HshSet集合对象

3、创建学生对象

4、把学生添加到集合

5、遍历集合(增强for)

6、在学生类中重写两个方法

(1)hashCode() 和 equals()

(2)自动生成即可

2 实现

2.1 方案一

Student.java

package HashSetDemo;

public class Student {
    private String name;
    private int age;

    // 无参构造
    public Student() {
    }

    // 带参构造
    public Student(String name, int age) {
        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;
    }
}

HashSetDemo02.java

package HashSetDemo;

import java.util.HashSet;

public class HashSetDemo02 {
    public static void main(String[] args) {

        // 创建HashSet集合对象
        HashSet<Student> hs = new HashSet<>();

        // 创建学生对象
        Student s1 = new Student("灰太狼", 20);
        Student s2 = new Student("懒洋洋", 21);
        Student s3 = new Student("导演", 22);

        Student s4 = new Student("导演", 23);

        // 把学生添加到集合
        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);

        // 遍历集合(增强for)
        for (Student s : hs) {
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

2.2 优化

Generate--> equals() and hashCode() 然后一直确定即可
Student.java

package HashSetDemo;

import java.util.Objects;

public class Student {
    private String name;
    private int age;

    // 无参构造
    public Student() {
    }

    // 带参构造
    public Student(String name, int age) {
        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;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

标签:

×
×