5-Set接口和常用方法

5-Set接口和常用方法

介绍汇总:

  1. Set接口基本介绍
  2. Set接口的常用方法
  3. Set接口的遍历方式
  4. 实践练习

1-Set接口基本介绍

  1. 无序(添加和取出的顺序不一致),没有索引
  2. 不允许重复元素,所以最多包含一个 null

2-Set接口的常用方法

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

3-Set接口的遍历方式

同 Collection 的遍历方式一样,因为 Set 接口是 Collection 接口的子接口。

  1. 可以使用迭代器
  2. 增强 for 循环
  3. 不能使用索引的方式获取(普通 for 循环方法)

4-实践练习

        Set set = new HashSet();

        // 添加方法
        // set 集合中数据无序,即添加顺序与取出顺序不一致,但是取出顺序是固定的
        // set 集合可以添加所有数据元素,但是不能重复,null 也只能放置一个,但是取出顺序中 null 永远为第一个
        set.add("jack") ;
        set.add("tom") ;
        set.add("jerry") ;
        set.add("marry") ;
        set.add("mike") ;
        set.add("jack") ;
        set.add(null) ;
        set.add(null) ;

        System.out.println("====HashSet集合中元素为" + set + "====");

        // 判断 set 集合中是否存在某元素
        if (set.contains(null)) {
            System.out.println("====HashSet集合中存在该元素====");
        }

        // 删除 set 集合中某元素
        if (set.remove(null)) {
            System.out.println("====HashSet集合中已删除某元素====");
        }



        System.out.println(">>>========迭代器遍历========<<<<");

        // 迭代器遍历 Set 集合
        Iterator iterator = set.iterator();

        while (iterator.hasNext()) {
            Object next =  iterator.next();
            System.out.println("====HashSet集合中元素为" + next + "====");
        }

        System.out.println(">>>========增强 for 循环遍历========<<<<");

        // 增强 for 循环遍历 Set 集合
        for (Object object : set) {
            System.out.println("====HashSet集合中元素为" + object + "====");
        }

        // set 集合无法使用普通 for 循环,即索引的方式
        // 虽然 set 集合拥有 size 方法,但是呢却没有 get 方法,无法使用索引遍历获取

posted on 2024-07-12 14:37  Yao_Happy  阅读(18)  评论(0编辑  收藏  举报