加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 05:33:07 所属栏目:Java 来源:网络整理
导读:问题: package day30_HashSet; import java.util.HashSet; /* * 通过hashset存储自定义对象,没有进行去重。** */ public class HashSetSutdentDemo { public static void main(String[] args) { // 创建集合对象 HashSetStudent hs = new HashSetStudent (

问题:

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 +
                ‘}‘;
    }
}

输出

?

?

解决:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读