• Java学习笔记 --- HashSet


    一、基本介绍

    1、HashSet 实现了 Set 接口

    2、HashSet 实际上是 HashMap 

    3、可以存放 null 值,但是只能有一个 null

    4、HashSet 不保证元素是有序的,取决于hash后,再确定索引的结果

    5、不能有重复元素/对象

    1. import java.util.HashSet;
    2. import java.util.Set;
    3. public class HashSet01 {
    4. public static void main(String[] args) {
    5. //1. 构造器的源码
    6. /*
    7. public HashSet() {
    8. map = new HashMap<>();
    9. }
    10. */
    11. //2. 可以存放null值,但是只能有一个,即元素不能重复
    12. Set hashSet = new HashSet();
    13. hashSet.add(null);
    14. hashSet.add(null);
    15. System.out.println(hashSet);
    16. //在执行add方法后,会返回一个boolean值
    17. //如果添加成功,返回true 否则返回false
    18. System.out.println(hashSet.add("张三"));//true
    19. System.out.println(hashSet.add("李四"));//true
    20. System.out.println(hashSet.add("老六"));//true
    21. System.out.println(hashSet.add("张三"));//false
    22. System.out.println(hashSet.add("铁蛋"));//true
    23. //可以通过remove指定删除哪个对象
    24. hashSet.remove("张三");
    25. System.out.println(hashSet);
    26. hashSet = new HashSet();
    27. hashSet.add("张三");//添加成功
    28. hashSet.add("张三");//添加失败
    29. hashSet.add(new Dog("小黑"));//添加成功
    30. hashSet.add(new Dog("小黑"));//添加成功
    31. System.out.println(hashSet);
    32. //经典面试题
    33. //看源码分析
    34. hashSet.add(new String("老六"));//加入成功
    35. hashSet.add(new String("老六"));//加入失败
    36. System.out.println(hashSet);
    37. }
    38. }
    39. class Dog {
    40. private String name;
    41. public Dog(String name) {
    42. this.name = name;
    43. }
    44. @Override
    45. public String toString() {
    46. return "Dog{" +
    47. "name='" + name + '\'' +
    48. '}';
    49. }
    50. }

    二、HashSet底层机制说明

    分析 HashSet 底层是 HashMap,HashMap 底层是(数组+链表+ 红黑树)

    1. public class HashSetStructure {
    2. public static void main(String[] args) {
    3. //1. 创建一个数组,数组的类型是 Node[]
    4. //2. 有些人直接把 Node[] 数组称为 表
    5. Node[] table = new Node[16];
    6. //3. 创建节点
    7. Node zs = new Node("张三", null);
    8. table[2] = zs;//将节点存放到数组的索引2的位置
    9. Node ls = new Node("李四", null);
    10. zs.next = ls;//将ls 节点挂载到 zs
    11. Node ll = new Node("老六", null);
    12. ls.next = ll;//将ll 节点挂载到 ls
    13. Node td = new Node("铁蛋", null);
    14. table[3] = td;//将节点存放到数组的索引3的位置
    15. System.out.println(table);
    16. }
    17. }
    18. class Node {//节点,存储数据࿰
  • 相关阅读:
    宝塔centos7安装Conda
    Allegro在板内添加器件限高区操作指导
    阿里云服务器上安装rabbitmq流程
    【分布式系统】Filebeat+Kafka+ELK 的服务部署
    ERROR: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
    YOLOv5 PyTorch TXT label文件格式讲解
    vue3和vue2生命周期​
    Java面试题之——异常和错误
    三个数之和
    Linux 服务器硬件及RAID配置实战
  • 原文地址:https://blog.csdn.net/a1404359447/article/details/127688663