• Set接口和常用方法


    Set接口和常用方法

    Set接口基本介绍

    • 无序 添加和取出的顺序不一致 没有索引
    • 不允许重复元素 所以最多包含一个null
    • Set接口实现类 常用 HashSet TreeSet

    Set接口的常用方法

    和List接口一样 Set接口也是Collection的子接口 常用方法和Collection接口一样

    Set接口的遍历方式

    同Collcetion遍历方式一样

    • 可以使用迭代器
    • 增强for
    • 不能使用索引方式来获取

    HashSet练习

    • 定义一个Employee类 包含name age
    • 创建三个对象放入HashSet中
    • 当name和age相同时 认为是相同员工 不能添加

    idea重写hashCode 调用add时 进行hash值判断 名字年龄相同 则返回相同hash

            HashSet hashSet = new HashSet();
    
            hashSet.add(new Employee("张三", 18)) ;
            hashSet.add(new Employee("李四", 20)) ;
            hashSet.add(new Employee("张三", 18)) ;
            
            
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Employee employee = (Employee) o;
            return age == employee.age && Objects.equals(name, employee.name);
        }
    
        @Override
        public int hashCode() {
            //idea重写hashCode 调用add时 进行hash值判断 名字年龄相同 则返回相同hash
            return Objects.hash(name, age);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    LinkedHashSet说明

    • LinkedHashSet是HashSet的子类
    • LinkedHashSet底层是一个LinkedHashMap 底层维护了一个 数组+双向链表
    • LinkedHashSet根据元素的hashCode值来决定元素的存储位置 同时使用链表维护元素的次序 这使得元素看起来是插入顺序保存的
    • LinkedHashSet不允许添加重复元素
  • 相关阅读:
    java 带括号 四则运算 计算器
    金仓数据库KingbaseES本地化支持(5. 字符集)
    云计算 | 中国信通院《2022 云计算白皮书》阅读、理解与总结
    C++的动态内存分配
    判断CGH40010F氮化镓管子的好坏-QSWL
    【golang】sorter 的两种实现方式
    stata的异方差检验
    redis cluster集群搭建
    php算法面试题及答案
    基于STM32设计的UNO卡牌游戏(双人、多人对战)
  • 原文地址:https://blog.csdn.net/keith32/article/details/125465656