利用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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章