Day16

07-19 1548阅读

Day16-集合

  • Day16 集合与迭代器
      • 1.1 集合的概念
      • 集合继承图
          • 1.2 Collection接口
            • 1、添加元素
            • 2、删除元素
            • 3、查询与获取元素
            • 不过当我们实际使用都是使用的他的子类Arraylist!!!
            • 1.3 API演示
              • 1、演示添加
              • 2、演示删除
              • 3、演示查询与获取元素
              • 2 Iterator迭代器
                • 2.1 Iterator接口
                • 2.2 迭代器的实现原理
                • 2.3 Iterable接口
                  • 1、 Iterable接口依赖Iterator接口
                  • 2、forEach方法
                  • 3、新语法糖:foreach循环(增强for循环)
                  • 2.4 使用Iterator迭代器删除元素
                  • 2.5 Iterator迭代器的快速失败(fail-fast)机制
                    • 1、ConcurrentModificationException异常
                    • 2、modCount变量
                    • 3 元素要求
                      • 3.1 有序、可重复
                        • 1、List接口介绍
                        • 2、List接口中常用方法
                        • 3、ListIterator迭代器
                        • 3.2 无序、不可重复
                          • 1、Set接口介绍
                          • 1.1HashSet
                          • 1.2TreeSet
                              • 2、元素相等和重复问题:equals和hashCode方法
                              • 3、大小顺序和重复问题:Comparable和Comparator接口
                              • 4 CollectionArray
                                • 4.1数组转换为集合的方法及注意事项
                                • 5removeif的使用
                                • 6 Collections 集合工具类

                                  Day16 集合与迭代器

                                  1.1 集合的概念

                                  集合是java中提供的一种容器,可以用来存储多个数据。

                                  集合和数组既然都是容器,它们有啥区别呢?

                                  • 数组的长度是固定的。
                                  • 集合的长度是可变的。
                                  • 数组中可以存储基本数据类型值,也可以存储对象,而集合中只能存储对象

                                    集合主要分为两大系列:Collection和Map,Collection 表示一组对象,Map表示一组映射关系或键值对。

                                    集合继承图

                                    Day16

                                    集合框架: 有序无序取决于能否用编号操作他

                                    Collection: 存储的是一个一个的数据
                                        -- List: 元素有序且允许重复
                                            -- ArrayList: 底层使用数组结构,查询快增删慢
                                            -- LinkedList: 底层使用双向链表结构,查询慢增删快
                                        -- Set: 元素无序且不允许重复
                                            -- HashSet: 底层使用哈希表结构
                                            -- TreeSet: 底层使用红黑树结构
                                            
                                    Map: 存储一对一对的数据
                                        -- HashMap:
                                        -- TreeMap:
                                        -- Hashtable:
                                    

                                    1.2 Collection接口

                                    Collection 层次结构中的根接口。Collection 表示一组对象,这些对象也称为 collection 的元素。一些 collection 允许有重复的元素,而另一些则不允许。一些 collection 是有序的,而另一些则是无序的。JDK 不提供此接口的任何直接实现:它提供更具体的子接口(如 Set 和 List、Queue)实现。此接口通常用来传递 collection,并在需要最大普遍性的地方操作这些 collection。

                                    Collection是所有单列集合的父接口,因此在Collection中定义了单列集合(List和Set)通用的一些方法,这些方法可用于操作所有的单列集合。方法如下:

                                    1、添加元素

                                    (1)add(E obj):添加元素对象到当前集合中

                                    (2)addAll(Collection coll):从当前集合中删除所有与coll集合中相同的元素。即this = this - this ∩ coll

                                    (3)boolean retainAll(Collection coll):从当前集合中删除两个集合中不同的元素,使得当前集合仅保留与c集合中的元素相同的元素,即当前集合中仅保留两个集合的交集,即this = this ∩ coll;

                                    (4)void clear():清空集合

                                    (5)boolean removeIf(Predicate c):判断c集合中的元素是否在当前集合中都存在。即c集合是否是当前集合的“子集”。

                                    (4)int size():获取当前集合中实际存储的元素个数

                                    (5)Object[] toArray():返回包含当前集合中所有元素的数组

                                    不过当我们实际使用都是使用的他的子类Arraylist!!!

                                    因为Java中使用ArrayList作为集合的一个常见选择,主要基于以下几个原因:

                                    1. 动态数组:ArrayList内部是通过一个动态数组来实现的,这意呀着它可以自动调整其大小以存储更多的元素。这种自动扩容的特性使得ArrayList在处理未知大小的数据集时非常方便。

                                    2. 随机访问:由于ArrayList是基于数组的,所以它可以提供快速的随机访问能力。也就是说,你可以通过索引(位置)直接访问或修改元素,这种操作的时间复杂度是O(1)。

                                    3. 易用性:ArrayList提供了丰富的API,使得添加、删除、查找元素等操作变得简单直观。它实现了List接口,因此可以使用所有List接口提供的方法。

                                    4. 广泛的使用场景:ArrayList适用于大多数需要列表功能的场景,包括存储对象集合、作为栈或队列的简单实现(尽管有专门的Stack和Queue接口及其实现),以及作为其他集合(如HashSet)的基础数据结构等。

                                    5. 性能考虑:尽管ArrayList在插入和删除元素时可能需要移动其他元素(这会影响性能,特别是在列表的开头或中间位置进行这些操作时),但在许多实际应用中,这种性能开销是可以接受的,特别是当元素添加和删除操作不频繁时。

                                    6. 与Java集合框架的兼容性:ArrayList是Java集合框架(Java Collections Framework)的一部分,这意味着它可以与其他集合类型(如Set、Map等)无缝协作,支持通过Collections类提供的静态方法(如排序、查找等)进行进一步的操作。

                                    然而,值得注意的是,ArrayList并不是所有情况下的最佳选择。例如,如果你需要频繁地在列表的开头或中间插入和删除元素,那么LinkedList可能会是更好的选择,因为它在这些操作上更加高效。同样,如果你需要一个不允许重复元素的列表,那么HashSet(通过其Set接口)或LinkedHashSet(保持元素插入顺序)可能是更合适的选择。选择哪种集合类型取决于你的具体需求和性能考虑。

                                    1.3 API演示

                                    1、演示添加

                                    注意:add和addAll的区别

                                    package com.atguigu.collection;
                                    import org.junit.Test;
                                    import java.util.ArrayList;
                                    import java.util.Collection;
                                    public class TestCollectionAdd {
                                        @Test
                                        public void testAdd(){
                                            //ArrayList是Collection的子接口List的实现类之一。
                                            Collection coll = new ArrayList();
                                            coll.add("小李广");
                                            coll.add("扫地僧");
                                            coll.add("石破天");
                                            System.out.println(coll);
                                        }
                                        @Test
                                        public void testAddAll(){
                                            Collection c1 = new ArrayList();
                                            c1.add(1);
                                            c1.add(2);
                                            System.out.println("c1集合元素的个数:" + c1.size());//2
                                            System.out.println("c1 = " + c1);
                                            Collection c2 = new ArrayList();
                                            c2.add(1);
                                            c2.add(2);
                                            System.out.println("c2集合元素的个数:" + c2.size());//2
                                            System.out.println("c2 = " + c2);
                                            Collection other = new ArrayList();
                                            other.add(1);
                                            other.add(2);
                                            other.add(3);
                                            System.out.println("other集合元素的个数:" + other.size());//3
                                            System.out.println("other = " + other);
                                            System.out.println();
                                            c1.addAll(other);
                                            System.out.println("c1集合元素的个数:" + c1.size());//5
                                            System.out.println("c1.addAll(other) = " + c1);
                                            c2.add(other);
                                            System.out.println("c2集合元素的个数:" + c2.size());
                                            System.out.println("c2.add(other) = " + c2);
                                        }
                                    }
                                    

                                    注意:coll.addAll(other);与coll.add(other);

                                    Day16

                                    2、演示删除

                                    注意几种删除方法的区别

                                    package com.atguigu.collection;
                                    import org.junit.Test;
                                    import java.util.ArrayList;
                                    import java.util.Collection;
                                    import java.util.function.Predicate;
                                    public class TestCollectionRemove {
                                        @Test
                                        public void test01(){
                                            Collection coll = new ArrayList();
                                            coll.add("小李广");
                                            coll.add("扫地僧");
                                            coll.add("石破天");
                                            coll.add("佛地魔");
                                            System.out.println("coll = " + coll);
                                            coll.remove("小李广");
                                            System.out.println("删除元素\"小李广\"之后coll = " + coll);
                                            coll.removeIf(new Predicate() {
                                                @Override
                                                public boolean test(Object o) {
                                                    String str = (String) o;
                                                    return str.contains("地");
                                                }
                                            });
                                            System.out.println("删除包含\"地\"字的元素之后coll = " + coll);
                                            coll.clear();
                                            System.out.println("coll清空之后,coll = " + coll);
                                        }
                                        @Test
                                        public void test02() {
                                            Collection coll = new ArrayList();
                                            coll.add("小李广");
                                            coll.add("扫地僧");
                                            coll.add("石破天");
                                            coll.add("佛地魔");
                                            System.out.println("coll = " + coll);
                                            Collection other = new ArrayList();
                                            other.add("小李广");
                                            other.add("扫地僧");
                                            other.add("尚硅谷");
                                            System.out.println("other = " + other);
                                            coll.removeAll(other);
                                            System.out.println("coll.removeAll(other)之后,coll = " + coll);
                                            System.out.println("coll.removeAll(other)之后,other = " + other);
                                        }
                                        @Test
                                        public void test03() {
                                            Collection coll = new ArrayList();
                                            coll.add("小李广");
                                            coll.add("扫地僧");
                                            coll.add("石破天");
                                            coll.add("佛地魔");
                                            System.out.println("coll = " + coll);
                                            Collection other = new ArrayList();
                                            other.add("小李广");
                                            other.add("扫地僧");
                                            other.add("尚硅谷");
                                            System.out.println("other = " + other);
                                            coll.retainAll(other);
                                            System.out.println("coll.retainAll(other)之后,coll = " + coll);
                                            System.out.println("coll.retainAll(other)之后,other = " + other);
                                        }
                                    }
                                    
                                    3、演示查询与获取元素
                                    package com.atguigu.collection;
                                    import org.junit.Test;
                                    import java.util.ArrayList;
                                    import java.util.Arrays;
                                    import java.util.Collection;
                                    public class TestCollectionContains {
                                        @Test
                                        public void test01() {
                                            Collection coll = new ArrayList();
                                            System.out.println("coll在添加元素之前,isEmpty = " + coll.isEmpty());
                                            coll.add("小李广");
                                            coll.add("扫地僧");
                                            coll.add("石破天");
                                            coll.add("佛地魔");
                                            System.out.println("coll的元素个数" + coll.size());
                                            Object[] objects = coll.toArray();
                                            System.out.println("用数组返回coll中所有元素:" + Arrays.toString(objects));
                                            System.out.println("coll在添加元素之后,isEmpty = " + coll.isEmpty());
                                            coll.clear();
                                            System.out.println("coll在clear之后,isEmpty = " + coll.isEmpty());
                                        }
                                        @Test
                                        public void test02() {
                                            Collection coll = new ArrayList();
                                            coll.add("小李广");
                                            coll.add("扫地僧");
                                            coll.add("石破天");
                                            coll.add("佛地魔");
                                            System.out.println("coll = " + coll);
                                            System.out.println("coll是否包含“小李广” = " + coll.contains("小李广"));
                                            System.out.println("coll是否包含“宋红康” = " + coll.contains("宋红康"));
                                            Collection other = new ArrayList();
                                            other.add("小李广");
                                            other.add("扫地僧");
                                            other.add("尚硅谷");
                                            System.out.println("other = " + other);
                                            System.out.println("coll.containsAll(other) = " + coll.containsAll(other));
                                        }
                                        @Test
                                        public void test03(){
                                            Collection c1 = new ArrayList();
                                            c1.add(1);
                                            c1.add(2);
                                            System.out.println("c1集合元素的个数:" + c1.size());//2
                                            System.out.println("c1 = " + c1);
                                            Collection c2 = new ArrayList();
                                            c2.add(1);
                                            c2.add(2);
                                            System.out.println("c2集合元素的个数:" + c2.size());//2
                                            System.out.println("c2 = " + c2);
                                            Collection other = new ArrayList();
                                            other.add(1);
                                            other.add(2);
                                            other.add(3);
                                            System.out.println("other集合元素的个数:" + other.size());//3
                                            System.out.println("other = " + other);
                                            System.out.println();
                                            c1.addAll(other);
                                            System.out.println("c1集合元素的个数:" + c1.size());//5
                                            System.out.println("c1.addAll(other) = " + c1);
                                            System.out.println("c1.contains(other) = " + c1.contains(other));
                                            System.out.println("c1.containsAll(other) = " + c1.containsAll(other));
                                            System.out.println();
                                            c2.add(other);
                                            System.out.println("c2集合元素的个数:" + c2.size());
                                            System.out.println("c2.add(other) = " + c2);
                                            System.out.println("c2.contains(other) = " + c2.contains(other));
                                            System.out.println("c2.containsAll(other) = " + c2.containsAll(other));
                                        }
                                    }
                                    

                                    2 Iterator迭代器

                                    2.1 Iterator接口

                                    在程序开发中,经常需要遍历集合中的所有元素。针对这种需求,JDK专门提供了一个接口java.util.Iterator。Iterator接口也是Java集合中的一员,但它与Collection、Map接口有所不同,Collection接口与Map接口主要用于存储元素,而Iterator主要用于迭代访问(即遍历)Collection中的元素,因此Iterator对象也被称为迭代器。

                                    想要遍历Collection集合,那么就要获取该集合迭代器完成迭代操作,下面介绍一下获取迭代器的方法:

                                    • public Iterator iterator(): iterator(): 获取到集合的迭代器,用来遍历集合里的元素。方法返回的结果是 Iterator类型的对象

                                      下面介绍一下迭代的概念:

                                      • 迭代:即Collection集合元素的通用获取方式。在取元素之前先要判断集合中有没有元素,如果有,就把这个元素取出来,继续在判断,如果还有就再取出出来。直到把集合中的所有元素全部取出。这种取出方式专业术语称为迭代。

                                        Iterator接口的常用方法如下:

                                        • public E next():返回迭代的下一个元素。
                                        • public boolean hasNext():如果仍有元素可以迭代,则返回 true。

                                          接下来我们通过案例学习如何使用Iterator迭代集合中元素:

                                          public class IteratorDemo {
                                              public static void main(String[] args) {
                                                  // List names = new ArrayList();
                                                  Set names = new HashSet();
                                                  names.add("tom");
                                                  names.add("jack");
                                                  names.add("jerry");
                                                  names.add("rose");
                                                  // 遍历集合元素的方式一: 使用 for循环(只能用于list)
                                                  /*for (int i = 0; i  
                                           
                                           

                                          提示:在进行集合元素取出时,如果集合中已经没有元素了,还继续使用迭代器的next方法,将会发生java.util.NoSuchElementException没有集合元素的错误。

                                          2.2 迭代器的实现原理

                                          我们在之前案例已经完成了Iterator遍历集合的整个过程。当遍历集合时,首先通过调用集合的iterator()方法获得迭代器对象,然后使用hashNext()方法判断集合中是否存在下一个元素,如果存在,则调用next()方法将元素取出,否则说明已到达了集合末尾,停止遍历元素。

                                          Iterator迭代器对象在遍历集合时,内部采用指针的方式来跟踪集合中的元素,接下来通过一个图例来演示Iterator对象迭代元素的过程:

                                          Day16

                                          在调用Iterator的next方法之前,迭代器指向第一个元素,当第一次调用迭代器的next方法时,返回第一个元素,然后迭代器的索引会向后移动一位,指向第二个元素,当再次调用next方法时,返回第二个元素,然后迭代器的索引会再向后移动一位,指向第三个元素,依此类推,直到hasNext方法返回false,表示到达了集合的末尾,终止对元素的遍历。

                                          2.3 Iterable接口

                                          1、 Iterable接口依赖Iterator接口

                                          java.lang.Iterable接口的抽象方法:

                                          • public Iterator iterator(): 获取对应的迭代器,用来遍历集合中的元素的。

                                            凡是实现了 Iterable接口的集合,就必须重写 iterator()方法,即还必须为该集合提供一个Iterator接口的实现类,否则就无法完成该方法的重写。

                                            2、forEach方法

                                            java.lang.Iterable接口在Java8还提供了一个forEach默认方法:

                                            • public default void forEach(Consumer
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]