java集合梳理【6】— Collections接口源码解析

本文详细解析了Java中的Collections接口,介绍了其作为工具类提供的不可变集合、同步集合、类型检查、空集合、singleton集合等功能。此外,还探讨了Collections接口中包括排序、二分搜索、反转、混排等常用方法的实现原理,并总结了Collections在集合操作中的重要作用。
摘要由CSDN通过智能技术生成

一、Collections接口是做什么的?

用官网文档的介绍:

The polymorphic algorithms described here are pieces of reusable functionality provided by the Java platform. All of them come from the Collections class, and all take the form of static methods whose first argument is the collection on which the operation is to be performed. The great majority of the algorithms provided by the Java platform operate on List instances, but a few of them operate on arbitrary Collection instances.(这里描述的多态算法是Java平台提供的可重用功能的一部分。它们都来自Collections类,都采用静态方法的形式,其第一个参数是要执行操作的集合。Java平台提供的绝大多数算法都对列表实例进行操作,但也有少数算法对任意集合实例进行操作。)

从介绍来看,这其实是一个工具类,实现了一些常用的算法,方便我们操作集合,如果没有这个类,也是可以的,就是自己写比较麻烦😂。但是呢,有了这个类,平时写代码我们可以直接调用(前提是了解里面怎么实现的,实现了什么功能),毕竟不是所有的轮子都要重复造。但是,不是有轮子了,我们就可以不去深究里面到底是啥,重要的不是造轮子,而是,我们必须有能够造轮子的能力

二、Collections源码之大类方法

1.提供不可变集合

一般是通过一个方法直接获取不可变的集合,里面包含了不可变的CollectionSetSortedSetNavigableSetListSortedMapNavigableMap

    // 获取不可变的Collection
    public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
   
        return new UnmodifiableCollection<>(c);
    }
    // 获取不可变的Set
    public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
   
        return new UnmodifiableSet<>(s);
    }
    // 获取不可变的SortedSet
   public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) {
   
        return new UnmodifiableSortedSet<>(s);
    }
    // 获取不可变的NavigableSet
    public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s) {
   
        return new UnmodifiableNavigableSet<>(s);
    }
    // 获取不可变的List
    public static <T> List<T> unmodifiableList(List<? extends T> list) {
   
        return (list instanceof RandomAccess ?
                new UnmodifiableRandomAccessList<>(list) :
                new UnmodifiableList<>(list));
    }
    // 获取不可变的SortedMap
    public static <K,V> SortedMap<K,V> unmodifiableSortedMap(SortedMap<K, ? extends V> m) {
   
        return new UnmodifiableSortedMap<>(m);
    }
    // 获取不可变的NavigableMap
    public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> m) {
   
        return new UnmodifiableNavigableMap<>(m);
    }

但是这些不可变的集合到底是什么呢?怎么使用呢?
我们来看一个最普遍的UnmodifiableCollection类的源码:

    // 实现了Collection和序列化接口
   static class UnmodifiableCollection<E> implements Collection<E>, Serializable {
   
        // 定义序列化的uid
        private static final long serialVersionUID = 1820017752578914078L;
        // 定义数据
        final Collection<? extends E> c;

        UnmodifiableCollection(Collection<? extends E> c) {
   
            if (c==null)
                throw new NullPointerException();
            this.c = c;
        }
        // 获取大小
        public int size()                   {
   return c.size();}
        // 是否为空
        public boolean isEmpty()            {
   return c.isEmpty();}
        // 是否包含
        public boolean contains(Object o)   {
   return c.contains(o);}
        // 转成数组
        public Object[] toArray()           {
   return c.toArray();}
        // 转成特定类型数组
        public <T> T[] toArray(T[] a)       {
   return c.toArray(a);}
        // toString方法
        public String toString()            {
   return c.toString();}
        // 获取迭代器
        public Iterator<E> iterator() {
   
            // 用内部类方式实现
            return new Iterator<E>() {
   
                // 迭代器其实是c的迭代器
                private final Iterator<? extends E> i = c.iterator();
                // 是否有下一个元素
                public boolean hasNext() {
   return i.hasNext();}
                // 获取下一个
                public E next()          {
   return i.next();}
                // 移除元素
                public void remove() {
   
                    throw new UnsupportedOperationException();
                }
                // 遍历剩下的元素
                @Override
                public void forEachRemaining(Consumer<? super E> action) {
   
                    // Use backing collection version
                    i.forEachRemaining(action);
                }
            };
        }
        // 增加操作抛异常
        public boolean add(E e) {
   
            throw new UnsupportedOperationException();
        }
        //删除操作抛异常
        public boolean remove(Object o) {
   
            throw new UnsupportedOperationException();
        }
        // 是否包含所有
        public boolean containsAll(Collection<?> coll) {
   
            return c.containsAll(coll);
        }
        // 批量添加操作抛异常
        public boolean addAll(Collection<? extends E> coll) {
   
            throw new UnsupportedOperationException();
        }
        // 批量删除抛异常
        public boolean removeAll(Collection<?> coll) {
   
            throw new UnsupportedOperationException();
        }
        // 取交集抛异常
        public boolean retainAll(Collection<?> coll) {
   
            throw new UnsupportedOperationException();
        }
        // 清空数据抛异常
        public void clear() {
   
            throw new UnsupportedOperationException();
        }

        // Override default methods in Collection
        @Override
        //遍历元素
        public void forEach(Consumer<? super E> action) {
   
            c.forEach(action);
        }
        // 按照条件移除元素抛异常
        @Override
        public boolean removeIf(Predicate<? super E> filter) {
   
            throw new UnsupportedOperationException();
        }
        // 获取可分割迭代器
        @SuppressWarnings("unchecked")
        @Override
        public Spliterator<E> spliterator() {
   
            return (Spliterator<E>)c.spliterator();
        }
        // 获取数据流
        @SuppressWarnings("unchecked")
        @Override
        public Stream<E> stream() {
   
            return (Stream<E>)c.stream();
        }
        // 获取并行流
        @SuppressWarnings("unchecked")
        @Override
        public Stream<E> parallelStream() {
   
            return (Stream<E>)c.parallelStream();
        }
    }

从上面的代码可以看出其实所谓不可变的集合,就是用一个包装类,持有对实际的集合的引用,只能执行查询操作,其他操作都会抛出异常UnsupportedOperationException。我们来看其他的,随便挑一个UnmodifiableMap:


    // 实现map接口和序列化接口
   private static class UnmodifiableMap<K,V> implements Map<K,V>, Serializable {
   
        // 序列号
        private static final long serialVersionUID = -1034234728574286014L;
        // 持有的引用
        private final Map<? extends K, ? extends V> m;
        // 初始化函数
        UnmodifiableMap(Map<? extends K, ? extends V> m) {
   
            if (m==null)
                throw new NullPointerException();
            this.m = m;
        }
        // 查询大小
        public int size()                        {
   return m.size();}
        // 是否为空
        public boolean isEmpty()                 {
   return m.isEmpty();}
        // 是否包含键
        public boolean containsKey(Object key)   {
   return m.containsKey(key);}
        // 是否包含值
        public boolean containsValue(Object val) {
   return m.containsValue(val);}
        // 通过值获取
        public V get(Object key)                 {
   return m.get(key);}
        // 添加(抛异常)
        public V put(K key, V value) {
   
            throw new UnsupportedOperationException();
        }
        // 删除元素(抛异常)
        public V remove(Object key) {
   
            throw new UnsupportedOperationException();
        }
        // 批量增加(抛异常)
        public void putAll(Map<? extends K, ? extends V> m) {
   
            throw new UnsupportedOperationException();
        }
        // 清空元素(抛异常)
        public void clear() {
   
            throw new UnsupportedOperationException();
        }
        // set的集合
        private transient Set<K> keySet;
        // ebtry的集合
        private transient Set<Map.Entry<K,V>> entrySet;
        // value的集合
        private transient Collection<V> values;
        // 获取key的集合
        public Set<K> keySet() {
   
            if (keySet==null)
                // 如果不为空,把keyset也变成一个不可变的集合之后再返回
                keySet = unmodifiableSet(m.keySet());
            return keySet;
        }

        public Set<Map.Entry<K,V>> entrySet() {
   
            if (entrySet==null)
                // 如果不为空,把entryset也变成一个不可变的集合之后再返回
                entrySet = new UnmodifiableEntrySet<>(m.entrySet());
            return entrySet;
        }

        public Collection<V> values() {
   
            if (values==null)
                // // 如果不为空,把value也变成一个不可变的集合之后再返回
                values = unmodifiableCollection(m.values());
            return values;
        }
        // 对象的方法判断是否相等,引用相等也是判断为相等
        public boolean equals(Object o) {
   return o == this || m.equals(o);}
        // 计算hash
        public int hashCode()           {
   return m.hashCode();}
        // toString法法
        public String toString()        {
   return m.toString();}

        // 重写方法,通过key获取vaule,没有则返回默认值
        @Override
        @SuppressWarnings("unchecked")
        public V getOrDefault(Object k, V defaultValue) {
   
            // Safe cast as we don't change the value
            return ((Map<K, V>)m).getOrDefault(k, defaultValue);
        }

        // 遍历执行action(动作参数化)
        @Override
        public void forEach(BiConsumer<? super K, ? super V> action) {
   
            m.forEach(action);
        }

        // 替换所有,抛异常
        @Override
        public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
   
            throw new UnsupportedOperationException();
        }
        // 如果不存在则放进去,抛异常
        @Override
        public V putIfAbsent(K key, V value) {
   
            throw new UnsupportedOperationException();
        }

        //删除操作,抛异常
        @Override
        public boolean remove(Object key, Object value) {
   
            throw new UnsupportedOperationException();
        }
        //替换操作,抛异常
        @Override
        public boolean replace(K key, V oldValue, V newValue) {
   
            throw new UnsupportedOperationException();
        }
        // 替换操作抛异常
        @Override
        public V replace(K key, V value) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值