Set Map集合

Set 无序 无下标 元素不可重复

方法 全部继承自Collection中的方法 

Set 实现类 HashSet  TreeSet

//Set接口使用
public class Dome {
    public static void main(String[] args) {
        //创建集合
        Set<String> set =new HashSet<String>();
        //添加数据
        set.add("苹果");

        set.add("华为");
        set.add("小米");
        System.out.println(set.size());
        System.out.println(set.toString());
        //删除元素
        //set.remove("小米");
        System.out.println(set.toString());
        //遍历
        for (String string:set ) {
            System.out.println(string.toString());

        }
        Iterator<String> it=set.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //判断
        System.out.println(set.contains("小米"));
        System.out.println(set.isEmpty());

HashSet    

//HashSet 存储结构 哈希表 (数组+链表)
public class HashDome {
    public static void main(String[] args) {
        HashSet<String> hashSet=new HashSet<String>();
        //添加元素
        hashSet.add("张三");
        hashSet.add("qwer");
        hashSet.add("ect");
        hashSet.add("Array");
        System.out.println(hashSet.size());
        System.out.println(hashSet.toString());
        //删除元素
        hashSet.remove("qwer");
        System.out.println(hashSet.toString());
        //遍历
        for (String string:hashSet
             ) {
            System.out.println(string.toString());
        }
        Iterator<String> it=hashSet.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //判断
        System.out.println(hashSet.contains("asdf"));
        System.out.println(hashSet.isEmpty());
    }
//存储过程 根据hashcode计算保存的位置 如果位置为空 则直接保存 如果不为空
//在执行equals 方法 如果equals方法为true 则认为是重复 否则 形成链表
public class HashDome1 {
    public static void main(String[] args) {
        HashSet<Person> hashSet=new HashSet<Person>();

        Person p1=new Person("面向",39);
        Person p2=new Person("襄阳",36);
        Person p3=new Person("相遇",37);
        //添加数据
        hashSet.add(p1);
        hashSet.add(p2);
        hashSet.add(p3);
        hashSet.add(new Person("相遇",37));
        System.out.println(hashSet.size());
        System.out.println(hashSet.toString());
        //删除数据
        //hashSet.remove(p1);
        //System.out.println(hashSet.size());
        //遍历
        for (Person person:hashSet
             ) {
            System.out.println(person.toString());
        }
        Iterator<Person> it= hashSet.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //判断
        System.out.println(hashSet.contains(p1));
        System.out.println(hashSet.isEmpty());
    }

TreeSet  基于排列顺序实现元素不重复  

                实现SortedSet接口 对集合元素自动排序

                元素对象类型必须实现Comparable 接口 指定排序规则

                通过CompareTo 方法确定是否为重复元素

//TreeSet的使用 存储结构 红黑树
// 元素必须要实现Comparable接口 compareTo()方法返回值为0 认为元素重复
public class TreeDome1 {
    public static void main(String[] args) {
        TreeSet<Person> treeSet=new TreeSet<Person>();
        Person p1=new Person("面向",39);
        Person p2=new Person("襄阳",36);
        Person p3=new Person("相遇",37);
        //添加元素
        treeSet.add(p1);
        treeSet.add(p2);
        treeSet.add(p3);
        System.out.println(treeSet.size());
        //删除元素
        //treeSet.remove(p1);
        //System.out.println(treeSet.toString());
        //遍历
        for (Person person:treeSet) {
            System.out.println(person.toString());

        }
        Iterator<Person> it=treeSet.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        //判断
        System.out.println(treeSet.contains(p1));
        System.out.println(treeSet.isEmpty());

    }
//先按姓名比 再按年龄比
@Override
public int compareTo(Person o) {
    int n1=this.getName().compareTo(o.getName());
    int n2=this.age-o.getAge();

    return n1==0?n2:n1;
}

Map 集合

         Map 接口特点 用于存储任意键值对 (key-Value)键:无序 无下标 不允许重复

                值:无序 无下标 允许重复

//Map 接口使用 存储 键值对 键不能重复 值可以重复 无序
public class MapDome1 {
    public static void main(String[] args) {
        //创建Map集合
        Map<String,String> map=new HashMap<String,String>();
        //添加元素
        map.put("cn","中国");
        map.put("am","美国");
        map.put("jp","日本");
       // map.put("cn","zhongguo"); 前边的就被替换了
        System.out.println(map.size());
        System.out.println(map.toString());
        //删除
       // map.remove("am");
      //  System.out.println(map.toString());
        //遍历  KeySet()方法
        Set<String> keyset=map.keySet();
        for (String key:keyset ) {
        System.out.println(key+""+map.get(key));
    }
        //使用 entrySet()方法
        Set<Map.Entry<String,String>>entries=map.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry.getKey()+""+entry.getValue());
        }
        //判断
        System.out.println(map.containsKey("am"));
        System.out.println(map.containsValue("俄罗斯"));
        System.out.println(map.isEmpty());
    }

Map 集合实现类  HashMap 线程不安全 运行效率快 允许用null 作为key 或者value

        HaSHMap刚创建时 table是null,为了节省空间 当添加第一个元素时table容量为16

        当元素个数大于阈值12时 会进行扩容 扩容后大小是原来的2倍目的减少调整元素个数

Hashtable 线程安全 运行效率慢 不允许null作为key和value 

Map 集合实现类 TreeMap  可以对key自动排序

//HashMap集合使用 存储结构 哈希表(数组+链表+红黑树)
public class HashDome {
    public static void main(String[] args) {
        //创建集合
        HashMap<Student,String> hashMap=new HashMap<Student,String>();
        Student s1=new Student("马",20);
        Student s2=new Student("向",21);
        Student s3=new Student("阳",22);
        //添加元素
        hashMap.put(s1,"尧都区");
        hashMap.put(s2,"洪洞");
        hashMap.put(s3,"临汾");
        //hashMap.put(new Student("阳",22),"临汾");
        System.out.println(hashMap.size());

        //删除元素
        //hashMap.remove(s1);
        //System.out.println(hashMap.toString());
        //遍历
        Set<Student> keyset=hashMap.keySet();
        for (Student key:keyset ) {
            System.out.println(key+""+hashMap.get(key));
        }
        Set<Map.Entry<Student,String>>entries=hashMap.entrySet();
        for (Map.Entry<Student, String> entry : entries) {
            System.out.println(entry.getKey()+""+entry.getValue());
        }
        //判断
        System.out.println(hashMap.containsKey(s2));
        System.out.println(hashMap.containsValue("临汾"));
        System.out.println(hashMap.isEmpty());
    }

Collections 工具类 

//Collections 工具类的使用
public class ColleDome {
    public static void main(String[] args) {
        List<Integer> list=new ArrayList<Integer>();
        list.add(23);
        list.add(5);
        list.add(78);
        list.add(54);
        //排序 sort
        Collections.sort(list);//从小到大
        System.out.println(list.toString());
        //binarySearch 二分查找
        int i=Collections.binarySearch(list,54);
        System.out.println(i);
        //reverse 反转
        Collections.reverse(list);
        System.out.println(list);
        //shuffle 打乱
        Collections.shuffle(list);
        System.out.println(list);
        //copy 复制
        List<Integer> dest=new ArrayList<Integer>();
        for (int j = 0; j < list.size(); j++) {
            dest.add(0);
        }
        Collections.copy(dest,list);
        System.out.println(list);

        //list 转成数组
        Integer[] array=list.toArray(new Integer[0]);
        System.out.println(array.length);
        System.out.println(Arrays.toString(array));
        //数组转成 list
        String[] names={"qwee","asdf","zxcvv"};
        List<String> list1=Arrays.asList(names);
        //集合是一个受限集合 不允许添加删除
        System.out.println(list1);
        //把基本类型转为集合 需要修改为包装类
        Integer[] nums={234,54,76,32};
        List<Integer> list2=Arrays.asList(nums);
        System.out.println(list2);
    }

        

<think> 我们正在讨论MapSet这两种数据结构。首先,我需要明确它们的基本概念、特点、对比以及使用场景。Map是键值对的集合,而Set是不重复元素的无序集合。然后,我将分别介绍它们的特点,进行对比,并说明各自的应用场景。最后,我会生成一些相关问题。 注意:在回答中,如果提到数学表达式,要遵循系统级指令,使用$...$或$$...$$格式。但由于当前问题不涉及数学公式,我将主要使用文字描述。 结构: 1. MapSet的基本概念 2. Map的特点 3. Set的特点 4. MapSet的对比(相同点和不同点) 5. 使用场景 6. 代码示例(如果需要) 7. 相关问题 由于用户要求对比、特点、使用场景,我将重点放在这些方面。 另外,由于用户提到“参考站内引用”,但当前没有具体的引用内容,我将根据通用知识进行回答。 </think>### Map集合Set集合对比分析 #### 一、基本概念对比 | 特性 | Map集合 | Set集合 | |--------------|----------------------------------|----------------------------------| | **数据结构** | 键值对(key-value)映射 | 唯一元素的无序集合 | | **存储单元** | Entry(key+value) | 单个元素 | | **重复规则** | Key不可重复,Value可重复 | 元素不可重复 | | **检索方式** | 通过Key获取Value | 直接检查元素存在性 | | **典型实现** | HashMap, TreeMap, LinkedHashMap | HashSet, TreeSet, LinkedHashSet | #### 二、核心特点 **Map核心特性**: 1. 键唯一性:每个Key最多映射一个Value 2. 高效查找:基于Key的哈希查找时间复杂度$O(1)$ 3. 有序变体:TreeMap提供$O(\log n)$有序访问 4. 空值支持:HashMap允许一个null key和多个null values **Set核心特性**: 1. 元素唯一性:自动去重(基于equals()和hashCode()) 2. 集合运算:支持并集/交集/差集等数学运算 3. 有序变体:TreeSet提供$O(\log n)$有序存储 4. 空值限制:HashSet允许一个null元素,TreeSet禁止null #### 三、使用场景对比 | **场景类型** | Map适用场景 | Set适用场景 | |--------------------|----------------------------------|----------------------------------| | **数据关联** | 用户ID-用户信息映射 | 独立数据如IP白名单 | | **快速检索** | 商品ID查询商品详情 | 敏感词过滤系统 | | **去重处理** | - | 日志去重/UV统计 | | **排序需求** | TreeMap实现键排序 | TreeSet实现元素排序 | | **关系映射** | 数据库外键关联缓存 | - | #### 四、Java实现示例 ```java // Map基础操作 Map<String, Integer> inventory = new HashMap<>(); inventory.put("Apple", 50); // 插入键值对 int count = inventory.get("Apple"); // 通过Key获取Value boolean exists = inventory.containsKey("Orange"); // 检查Key存在性 // Set基础操作 Set<String> uniqueWords = new HashSet<>(); uniqueWords.add("algorithm"); // 添加元素 boolean contains = uniqueWords.contains("data"); // 检查元素存在 uniqueWords.remove("set"); // 删除元素 ``` #### 五、性能对比 | **操作** | HashMap | TreeMap | HashSet | TreeSet | |---------------|---------|---------|---------|---------| | **插入** | $O(1)$ | $O(\log n)$ | $O(1)$ | $O(\log n)$ | | **查询** | $O(1)$ | $O(\log n)$ | $O(1)$ | $O(\log n)$ | | **内存占用** | 较高 | 中等 | 较低 | 中等 | | **顺序保证** | 无 | 按键排序 | 无 | 按元素排序 | #### 六、特殊类型应用 1. **WeakHashMap**:实现内存敏感缓存(键被GC回收时自动移除条目) 2. **EnumSet**:高效存储枚举值(底层位向量实现) 3. **IdentityHashMap**:使用==代替equals()比较键对象 4. **CopyOnWriteArraySet**:线程安全Set(读操作无锁) > 选择建议:需要键值关联用Map,只需元素唯一性用Set;需要排序选Tree系列,需要插入顺序保持选Linked系列,高并发环境考虑ConcurrentHashMap/ConcurrentSkipListSet[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值