当前位置:网站首页>HashSet集合存储学生对象并遍历

HashSet集合存储学生对象并遍历

2022-06-11 17:58:00 m0_60087722

package com.study.exception.demo22;

import java.util.HashSet;

public class HashSetStudent {

    /*
    需求:创建一个存储学生对象的集合,存储多个学生对象,使用程序实现 在控制台遍历该集合
        要求:学生对象的成员变量值相同,则认为是同一个对象
    思路:
    1.定义学生类
    2.创建HashSet集合对象
    3.创建学生对象
    4.把学生添加到集合
    5.遍历集合(增强for)
     */
    public static void main(String[] args) {
        HashSet<Student> hs = new HashSet<>();

        Student s1 = new Student("张三",30);
        Student s2= new Student("李四",33);
        Student s3 = new Student("王五",35);
        Student s4= new Student("李四",33);

        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);

        for (Student s : hs) {
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}
package com.study.exception.demo22;

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;

        if (age != student.age) return false;
        return name.equals(student.name);
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + age;
        return result;
    }
}
原网站

版权声明
本文为[m0_60087722]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_60087722/article/details/125074867