为什么HashSet包含多个相同的对象?

时间:2017-10-01 10:50:30

标签: java

这是我的代码,结果显示HashSet包含多个相同的对象。但我无法理解为什么HashSet可以包含多个相同的对象。我已经覆盖了equals()和hashCode()方法。

import java.util.HashSet;
public class HashFunction {
    public static class Student {
        public int id;
        public String name;

        public Student(int id, String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Student)) return false;

            Student student = (Student) o;

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

        }

        @Override
        public int hashCode() {
            int result = id;
            result = 31 * result + name.hashCode();
            return result;
        }
    }

    public static void main(String[] args) {
        HashSet<Student> set = new HashSet<Student>(1, 0.5f);
        Student s1 = new Student(1, "aa");
        Student s2 = new Student(2, "bb");

        set.add(s1);
        set.add(s2);
        System.out.println(set);

        Student s3 = s1;
        s3.id = 3;
        set.add(s3);
        System.out.println(s1.equals(s3));
        System.out.println(s1.hashCode() == s3.hashCode());

        for (Student s: set) {
            System.out.println(s.hashCode());
        }
        System.out.println(set);
    }
}

结果:

[HashFunction$Student@c7e, HashFunction$Student@c3f]
 true
 true
 3197
 3198
 3197
 [HashFunction$Student@c7d, HashFunction$Student@c7e, HashFunction$Student@c7d]

0 个答案:

没有答案