Java进阶:【集合】set接口

x33g5p2x  于2021-11-27 转载在 Java  
字(1.3k)|赞(0)|评价(0)|浏览(297)

set接口

特点:无序,唯一,这里的无序是相对list来说的,不是随机,

API:相对于list,没有索引的相关方法,

那么证明我们的遍历方法有:

(1)迭代器

(2)增强for循环

hashset实现类使用

无序,唯一,我们会发现重复存放的元素,输出的时候只会有一个,那如何验证呢,add()是一个bool返回值方法,所以我们输出add方法来看看去呗

我们可以发现,第一次添加hello,的返回结果时true成功的,第二次重复的时候就是false失败的,

public static void main(String[] args) {
        HashSet<String> hs = new HashSet<>();
        System.out.println(hs.add("hello")); //true
        hs.add("hello");
        hs.add("hi");
        hs.add("html");
        hs.add("apple");
        hs.add("hello");
        System.out.println(hs.add("hello"));//false
        System.out.println(hs);
        System.out.println(hs.size());
    }

自定义引用类型的数据:

public static void main(String[] args) {
        HashSet<Student> hs = new HashSet<>();
        hs.add(new Student("小丽",19));
        hs.add(new Student("小hu",29));
        hs.add(new Student("小Li",39));
        hs.add(new Student("小tian",49));
        hs.add(new Student("小丽",19));

        System.out.println(hs.toString());
    }

我自定义的类型不满足,唯一,无序的特点,为什么呢?

HashSet简要原理图

原因:我们的Student类没有重写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 &&
                name.equals(student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

重写之后,就符合HashSet的无序,唯一的特性了

hashSet原理:

底层与hashmap十分相似,下图是属性和构造器的分析

collection总结图

相关文章

微信公众号

最新文章

更多