Java中HashSet集合存储自定义类型

一,集合存储元素不重复原理

HashSet集合对象在调用add方法时,会调用元素的hashCode()方法和equals()方法,两方法返回值一致时判定为重复元素。
在这里插入图片描述

二,HashSet集合存储自定义元素

set集合保证元素唯一:
存储的元素(String,Integer…Student,Person…),必须重写hashCode()方法和equals()方法。
重写的方法如下:

    @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);
    }
public class DemoHashSetSaveStudent {
    public static void main(String[] args) {
        HashSet<Student> set = new HashSet<>();
        Student s1 = new Student("小军",18);
        Student s2 = new Student("小军",18);
        Student s3 = new Student("小红", 19);
        set.add(s1);
        set.add(s2);
        set.add(s3);
        System.out.println(set);
        //[Student{name='小军', age=18}, Student{name='小红', age=19}, Student{name='小军', age=18}]
        //[Student{name='小军', age=18}, Student{name='小红', age=19}]
        System.out.println(s1.hashCode());//1967205423|23296487
        System.out.println(s2.hashCode());//42121758  |23296487
        System.out.println(s1 == s2); //false  | false
        System.out.println(s1.equals(s2)); //false | true
        System.out.println(s3.hashCode());//20671747  | 23653825
    }
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值