当前位置:网站首页>Case -- the HashSet set stores the student object and traverses

Case -- the HashSet set stores the student object and traverses

2022-06-13 05:05:00 Jason_ LH1024

 

package com.it;

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;
    }

    // rewrite equals and hashCode Method 
    @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);
    }
}

 

package com.it;

import java.util.HashSet;

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

        // establish HashSet A collection of objects 
        HashSet<Student> hs = new HashSet<>();

        Student s1 = new Student(" Huairong ", 23);
        Student s2 = new Student(" brother ", 22);
        Student s3 = new Student(" Sure ", 21);

        Student s4 = new Student(" Huairong ", 23);
        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);

        for (Student s : hs) {
            System.out.println(s.getName() + "," + s.getAge());
        }

    }
}

原网站

版权声明
本文为[Jason_ LH1024]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280515588094.html