30.1 HashSet存储自定义对象 未去重解决

问题:

package day30_HashSet;

import java.util.HashSet;

/*
* 通过hashset存储自定义对象,没有进行去重。
*
* */
public class HashSetSutdentDemo {

    public static void main(String[] args) {
        //创建集合对象
        HashSet<Student> hs = new HashSet<Student>();

        //创建元素对象
        Student st = new Student("aa",20);
        Student st2 = new Student("bb",18);
        Student st3 = new Student("bb",18);
        //添加元素对象
        hs.add(st);
        hs.add(st2);
        hs.add(st3);

        //遍历集合对象
        for (Student s : hs) {
            System.out.println(s);
        }


    }
}

class Student {
    String name;
    int age;

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

    @Override
    public String toString() { //默认输出的是student的地址值,重写tostring方法
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

输出

 

 

解决:

HashSet 的 add方法使用的是 hashcode 和equals进行比较

需要重写hashcode 和equals

package day30_HashSet;

import java.util.HashSet;
import java.util.Objects;

/*
 *    使用HashSet存储自定义对象并遍历
 *    通过查看源码发现:
 *                HashSet的add()方法,首先会使用当前集合中的每一个元素和新添加的元素进行hash值比较,
 *                如果hash值不一样,则直接添加新的元素
 *                如果hash值一样,比较地址值或者使用equals方法进行比较
 *                比较结果一样,则认为是重复不添加
 *                所有的比较结果都不一样则添加

 */
public class HashSetStudentDemo2 {
    public static void main(String[] args) {
        HashSet<Student2> hs = new HashSet<Student2>();
        //创建元素对象
        Student2 s = new Student2("zhangsan",18);
        Student2 s2 = new Student2("lisi",19);
        Student2 s3 = new Student2("lisi",19);
        //添加元素对象
        hs.add(s);
        hs.add(s2);
        hs.add(s3);
        //遍历集合对象
        for (Student2 student : hs) {
            System.out.println(student);
        }
    }
}

class Student2 {
    String name;
    int age;

    public Student2(String name,int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student2{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student2 student2 = (Student2) o;
        return age == student2.age &&
                Objects.equals(name, student2.name);
    }

    @Override
    public int hashCode() {

        return Objects.hash(name, age);
    }
}

 

转载于:https://www.cnblogs.com/longesang/p/11269046.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值