Java中hashCode问题详细解析(2)

public class Student {
    private String name;
    private int age;
    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;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if(!(obj instanceof Student)){
            System.out.println("类型错误");
            return false;
        }
        Student other = (Student) obj;
        return this.age ==  other.age && this.name.equals(other.name);
    }
}

创建HashSet集合,存储Student对象

public class HashSetDemo {
    public static void main(String[] args) {
        //创建HashSet对象
        HashSet<Student> hs = new<Student> HashSet();
        //给集合中添加自定义对象
        hs.add(new Student("zhangsan",21));
        hs.add(new Student("lisi",22));
        hs.add(new Student("wangwu",23));
        hs.add(new Student("zhangsan",21));
        //取出集合中的每个元素
        Iterator it = hs.iterator();
        while(it.hasNext()){
            Student s = (Student)it.next();
            System.out.println(s);
        }
    }
}

输出结果:

Student [name=lisi, age=22]
Student [name=zhangsan, age=21]
Student [name=wangwu, age=23]

7. 写在后面

保证HashSet集合元素的唯一,其实就是根据对象的hashCode和equals方法来决定的。如果我们往集合中存放自定义的对象,那么保证其唯一,就必须重写hashCode和equals方法建立属于当前对象的比较方式。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/0c2eb8c56d2669d67d796cb2cd934a4c.html