Java 集合 源码分析+重点解析 超详细学习资料

集合

我这次不讲解用法,要知道怎么用,去翻阅 API 文档就好了,我这里,就稍微品尝一下集合的源码

这里,我先放上集合的所有继承关系图:

image-20210503160621439

————单值存储————

Collection

下面就是 Collection 的源码,所有集合,都要实现 Collection接口

在早期,都是用 Collection 去指向集合实现的,但是因为无法区分 List 和 Set (主要是有取消重复元素的需要),所以,Sun 在开源项目 PetShop 中,开始推荐使用 List 和 Set 来指向集合的实现

public interface Collection<E> extends Iterable<E> {
   
   //返回大小
    int size();
  //是否为空
    boolean isEmpty();
	//是否包含
    boolean contains(Object o);
	//迭代器
    Iterator<E> iterator();
	//将所包含的元素,
    Object[] toArray();

    <T> T[] toArray(T[] a);

    // Modification Operations

	  //增加元素
    boolean add(E e);

    //删除指定元素
    boolean remove(Object o);


    // Bulk Operations

   //判断当前集合是否包含传入集合的所有元素
    boolean containsAll(Collection<?> c);

   //将传入集合的所有元素,放入当前集合
    boolean addAll(Collection<? extends E> c);

   
    boolean removeAll(Collection<?> c);

    default boolean removeIf(Predicate<? super E> filter) {
   
        Objects.requireNonNull(filter);
        boolean removed = false;
        final Iterator<E> each = iterator();
        while (each.hasNext()) {
   
            if (filter.test(each.next())) {
   
                each.remove();
                removed = true;
            }
        }
        return removed;
    }

   //和传入的集合,取交集
    boolean retainAll(Collection<?> c);

   
    void clear();


    // Comparison and hashing

   
    boolean equals(Object o);

    int hashCode();

    @Override
    default Spliterator<E> spliterator() {
   
        return Spliterators.spliterator(this, 0);
    }

  //java8新增的 stream 流操作 
    default Stream<E> stream() {
   
        return StreamSupport.stream(spliterator(), false);
    }

    default Stream<E> parallelStream() {
   
        return StreamSupport.stream(spliterator(), true);
    }
}

源码的注释中,还给出了 Collection 的所有子类:

* @see     Set
 * @see     List
 * @see     Map
 * @see     SortedSet
 * @see     SortedMap
 * @see     HashSet
 * @see     TreeSet
 * @see     ArrayList
 * @see     LinkedList
 * @see     Vector
 * @see     Collections
 * @see     Arrays
 * @see     AbstractCollection

List

继承 Collection 接口,也添加了自己特殊的接口方法

public interface List<E> extends Collection<E> {
   
  //...
}

相对于 Collection,添加的方法

image-20210503143811553

ArrayList

这里,我们就小尝一下 ArrayList 的源码

ArrayList 在未被指定大小的时候,会默认申请一个长度为 10 的空间

如果在 add 的时候,长度不够,会扩容 1.5 倍

ArrayList,是线程不安全的,所以效率比 Vector 高(Vector 线程安全)

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FARO_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值