利用HashSet,存储自定义的对象,通过重写自定义对象中hashCode和equals方法保证存储元素的唯一性

public class HashSetTest {

    public static void main(String[] args) {
        // 创建集合对象
        HashSet<Student> studentHashSet = new HashSet<Student>();
        // 创建学生对象
        Student s1 = new Student("张三", 27);
        Student s2 = new Student("李四", 22);
        Student s3 = new Student("王五", 30);
        Student s4 = new Student("张三", 27);
        Student s5 = new Student("张三", 20);
        Student s6 = new Student("何六", 22);
        // 添加元素
        studentHashSet.add(s1);
        studentHashSet.add(s2);
        studentHashSet.add(s3);
        studentHashSet.add(s4);
        studentHashSet.add(s5);
        studentHashSet.add(s6);
        // 遍历集合
        for (Student s : studentHashSet) {
            System.out.println(s.getName() + "---" + s.getAge());
        }
    }

    static class Student {
        private String name;
        private int age;
        public Student() {
            super();
        }
        public Student(String name, int age) {
            super();
            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;
        }

        /**
         * 重写equals方法
         * @param o
         * @return
         */
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Student)) return false;
            Student student = (Student) o;
            if (age != student.age) return false;
            if (!name.equals(student.name)) return false;
            return true;
        }

        /**
         * 重写hashCode方法
         * @return
         */
        @Override
        public int hashCode() {
            int result = name.hashCode();
            result = 31 * result + age;
            return result;
        }
    }
}

发布了68 篇原创文章 · 获赞 32 · 访问量 10万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章