集合(14):Collection下的子接口----set接口,set接口的子类----HashSet类

集合(14):Collection下的子接口:set接口,set接口的子类----HashSet类

一、set集合的介绍

1、set集合的概述
元素唯一且元素无序(存储和取出顺序不一致)的集合
2、我们需要学习set接口的三个子类:HashSet类、LinkedHashSet类、TreeSet类

二、set集合的HashSet类

HashSet类

不保证set的迭代顺序(输出的结果是无序的),特别是不保证该顺序恒久不变

1、HashSet类的使用案例一
import java.util.HashSet;
public class SetDemo1 {
    public static void main(String[] args) {
        //set是一个接口,不能实例化,用它的一个子类HashSet创建对象
        HashSet<String> arr = new HashSet<>();

        //添加元素到集合
        arr.add("hello");
        arr.add("world");
        arr.add("java");
        arr.add("bigdata");
        arr.add("hadoop");
        arr.add("hello");
        arr.add("hello");
        arr.add("java");
        arr.add("spark");
        arr.add("flink");
        arr.add("world");
        arr.add("hadoop");
		//使用增强for循环遍历
        for(String s : arr){
            System.out.println(s);
        }
    }
}
            执行结果如下:
                        flink
                        world
                        java
                        bigdata
                        spark
                        hello
                        hadoop

                        Process finished with exit code 0
                /*
                	由此可知,可以想set集合中添加相同的元素
                	最终遍历出来的元素是没有相同的
                */
2、分析Set集合中的元素为什么不会重复,看源码
按住Ctrl+鼠标左击add

源码分析:

3、HashSet类的使用案例二
import java.util.HashSet;

/*
        存储自定义对象并遍历
 */
public class HashSetDemo2 {
    public static void main(String[] args) {
        //创建集合对象
        HashSet<Student2> hashSet = new HashSet<>();

        //创建学生对象
        Student2 s1 = new Student2("xiaowang", 18);
        Student2 s2 = new Student2("xiaowang", 18);
        Student2 s3 = new Student2("xiaoli", 19);
        Student2 s4 = new Student2("xiaoliu", 20);

        hashSet.add(s1);
        hashSet.add(s2);
        hashSet.add(s3);
        hashSet.add(s4);

        for(Student2 s:hashSet){
            System.out.println(s);
        }
    }
}
            执行结果如下:
                        Student2{name='xiaowang', age=18}
                        Student2{name='xiaoli', age=19}
                        Student2{name='xiaoliu', age=20}

                        Process finished with exit code 0

注意:

在遍历自定义对象的时候,第一步需要先创建一个学生类

如果在遍历的时候,最后的结果没有去重,说明学生类中没有重写equals()和hashCode()

只需在学生类中,利用快捷键添加equals()和hashCode()即可

4、HashSet如何保证元素的唯一性

(1)底层数据结构是哈希表(元素是链表的数组)

(2)哈希表依赖于 哈希值存储

(3)添加功能底层依赖两个方法

①int hashCode()

②boolean equals(Object obj)

posted @ 2021-12-30 00:19  阿伟宝座  阅读(68)  评论(0)    收藏  举报