【JDK】ArrayList集合 源码阅读
这是博主第二次读ArrayList 源码,第一次是在很久之前了,当时读起来有些费劲,记得那时候HashMap的源码还是哈希表+链表的数据结构。
时隔多年,再次阅读起来ArrayList感觉还蛮简单的,但是HashMap已经不是当年的HashMap了,所以下一篇会写HashMap的。
起因:最近写了一个简单的文件校验方法,然后犯了一些比较低级的错误,博主的师兄在进行发布CR时,提出了一些建议,博主感觉羞愧难当,特此记录一下,诸君共勉。代码以及建议如下,已做脱敏处理:
    /**
     * 修改前
     */
    public String checkFileWithJveye() {
        //建立 sftp链接,获取目录下所有文件列表集合
        List<String> remoteSftpFileList = getRemoteSftpFileList();
        //获取服务器已下载列表文件集合(以XXX结尾的)
        List<String> localFileList = getLocalFileList();
        //已经存在的文件-remove
        for (int i = 0; i < remoteSftpFileList.size(); i++) {
            if (localFileList.contains(remoteSftpFileList.get(i))) {
                remoteSftpFileList.remove(i);
            }
        }
        return remoteSftpFileList.toString();
    }
/**
 * 师兄的批注:
 * Master @XXXX 大约 6 小时之前
 *         不应该在循环内进行 list.remove(index) 操作,当remove一个元素之后,
 *         list会调整顺序,size() 会重新计算len,但是i还是原来的值,
 *         导致list有些值没有被循环到。推荐使用迭代器 list.iterator(),
 *         或者将返回的类型改为set,空间换时间,这样速度也能快些。
 * 讨论中师兄从源码方面解释了ArrayList使用的是遍历Remove,而HashSet直接通过Hash值进行Remove效率更高。
 */
    /**
     * 修改后
     */
    public String checkFileWithJveye2() {
        //建立 sftp链接,获取目录下所有文件列表集合
        Set<String> remoteSftpFiles = getRemoteSftpFileList();
        //获取服务器已下载列表文件集合(以XXX结尾的)
        Set<String> localFiles = getLocalFileList();
        //已经存在的文件-remove
        for (Iterator<String> it = remoteSftpFiles.iterator(); it.hasNext(); ) {
            String fileName = it.next();
            if (localFiles.contains(fileName)) {
                it.remove();
            }
        }
        //返回未获取文件的列表
        return remoteSftpFiles.toString();
    }
因此博主重读了ArrayList等源代码,都是复制的源代码,方便阅读,省去了很多年东西(本来东西也不多),只有简单的增删改,继承关系图如下:

代码如下:
import java.util.*;
/**
 * ArrayList简单的增删改查
 * @param <E>
 */
public class Bag<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
    /**
     * Default initial capacity.
     * 默认的初始化容量
     */
    private static final int DEFAULT_CAPACITY = 10;
    /**
     * Shared empty array instance used for empty instances.
     * EMPTY_CAPACITY
     */
    //private static final Object[] EMPTY_ELEMENTDATA = {};
    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish(辨别,分清) this from EMPTY_ELEMENTDATA to know how much to inflate(增长) when
     * first element is added.
     * DEFAULT_CAPACITY
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     *
     * non-private to simplify nested class access      非私有简化嵌套类的使用。
     */
    transient Object[] elementData;
    /**
     * The size of the ArrayList (the number of elements it contains).
     * 集合中元素的个数
     * @serial
     */
    private int size;
    /**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     * 最大容量
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    /**
     * Constructs an empty list with an initial capacity of ten.
     * 初始化构造方法-这里只保留了一个
     */
    public Bag() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    /**
     * 增
     * Appends the specified element to the end of this list.
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    @Override
    public boolean add(E e) {
        // Increments modCount!!
        ensureCapacityInternal(size + 1);
        elementData[size++] = e;
        return true;
    }
    public void ensureCapacityInternal(int minCsap){
        minCsap=minCsap>=DEFAULT_CAPACITY?minCsap:DEFAULT_CAPACITY;
        if (minCsap - elementData.length > 0){
            grow(minCsap);
        }
    }
    /**
     * 查
     * Returns the element at the specified position in this list.
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    @Override
    public E get(int index) {
        if (index >= size){
            throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size());
        }
        return elementData(index);
    }
    // Positional Access Operations
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }
    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by(由。。。指定) the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0){
            newCapacity = minCapacity;
        }
        if (newCapacity - MAX_ARRAY_SIZE > 0){
            newCapacity = hugeCapacity(minCapacity);
        }
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    private static int hugeCapacity(int minCapacity) {
        // overflow
        if (minCapacity < 0){
            throw new OutOfMemoryError
                    ("Required array size too large");
        }
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }
    /**
     *删
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    @Override
    public E remove(int index) {
        //验证index
        rangeCheck(index);
        E oldValue = elementData(index);
        int numMoved = size - index - 1;
        if (numMoved > 0){
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        }
        // clear to let GC do its work?
        elementData[--size] = null;
        return oldValue;
    }
    private void rangeCheck(int index) {
        if (index >= size){
            throw new IndexOutOfBoundsException("Index:+index+, Size: +size()");
        }
    }
    /**
     * 删
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    @Override
    public boolean remove(Object o){
        if(o==null){
            for (int i=0;i<elementData.length;i++){
                if(elementData[i]==null){
                    fastRemove(i);
                    return true;
                }
            }
        }else{
            for (int i=0;i<elementData.length;i++){
                if(o.equals(elementData[i])){
                    fastRemove(i);
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * arrayCopy( arr1, 2, arr2, 5, 10);
     * 意思是;将arr1数组里从索引为2的元素开始, 复制到数组arr2里的索引为5的位置, 复制的元素个数为10个.
     */
    private void fastRemove(int index){
        int numMoved = size - index - 1;
        if (numMoved > 0){
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        }
        // clear to let GC do its work
        elementData[--size] = null;
    }
    /**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    @Override
    public int size() {
        return size;
    }
    /**
     * Returns <tt>true</tt> if this list contains no elements.
     *
     * @return <tt>true</tt> if this list contains no elements
     */
    @Override
    public boolean isEmpty() {
        return size == 0;
    }
}
												
											【JDK】ArrayList集合 源码阅读的更多相关文章
- java1.7集合源码阅读: Stack
		
Stack类也是List接口的一种实现,也是一个有着非常长历史的实现,从jdk1.0开始就有了这个实现. Stack是一种基于后进先出队列的实现(last-in-first-out (LIFO)),实 ...
 - java1.7集合源码阅读: Vector
		
Vector是List接口的另一实现,有非常长的历史了,从jdk1.0开始就有Vector了,先于ArrayList出现,与ArrayList的最大区别是:Vector 是线程安全的,简单浏览一下Ve ...
 - 【JDK1.8】JDK1.8集合源码阅读——IdentityHashMap
		
一.前言 今天我们来看一下本次集合源码阅读里的最后一个Map--IdentityHashMap.这个Map之所以放在最后是因为它用到的情况最少,也相较于其他的map来说比较特殊.就笔者来说,到目前为止 ...
 - 【JDK1.8】JDK1.8集合源码阅读——ArrayList
		
一.前言 在前面几篇,我们已经学习了常见了Map,下面开始阅读实现Collection接口的常见的实现类.在有了之前源码的铺垫之后,我们后面的阅读之路将会变得简单很多,因为很多Collection的结 ...
 - JDK 1.8源码阅读  ArrayList
		
一,前言 ArrayList是Java开发中使用比较频繁的一个类,通过对源码的解读,可以了解ArrayList的内部结构以及实现方法,清楚它的优缺点,以便我们在编程时灵活运用. 二,ArrayList ...
 - 【JDK1.8】JDK1.8集合源码阅读——总章
		
一.前言 今天开始阅读jdk1.8的集合部分,平时在写项目的时候,用到的最多的部分可能就是Java的集合框架,通过阅读集合框架源码,了解其内部的数据结构实现,能够深入理解各个集合的性能特性,并且能够帮 ...
 - 【JDK1.8】JDK1.8集合源码阅读——HashMap
		
一.前言 笔者之前看过一篇关于jdk1.8的HashMap源码分析,作者对里面的解读很到位,将代码里关键的地方都说了一遍,值得推荐.笔者也会顺着他的顺序来阅读一遍,除了基础的方法外,添加了其他补充内容 ...
 - 【JDK1.8】JDK1.8集合源码阅读——LinkedList
		
一.前言 这次我们来看一下常见的List中的第二个--LinkedList,在前面分析ArrayList的时候,我们提到,LinkedList是链表的结构,其实它跟我们在分析map的时候讲到的Link ...
 - JDK 1.8源码阅读  TreeMap
		
一,前言 TreeMap:基于红黑树实现的,TreeMap是有序的. 二,TreeMap结构 2.1 红黑树结构 红黑树又称红-黑二叉树,它首先是一颗二叉树,它具体二叉树所有的特性.同时红黑树更是一颗 ...
 
随机推荐
- SCJP考试题310-025(第二套<4>)92-147/147
			
310-025 Leading the way in IT testing and certification tools,QUESTION NO: 92 Given: 1. String foo = ...
 - C# Winform在win10里弹出无焦点的窗口
			
原文:C# Winform在win10里弹出无焦点的窗口 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/wangmy1988/article/det ...
 - 罚函数(penalty function)的设计
			
1. encourage sparsity ℓ0 范数: non-differentiable and difficult to optimize in general ℓ1 范数: 对数约束,log ...
 - 好用的Markdown 编辑器及工具
			
Markdown 是 2004 年由 John Gruberis 设计和开发的纯文本格式的语法,所以通过同一个名字它可以使用工具来转换成 HTML.readme 文件,在线论坛编写消息和快速创建富文本 ...
 - PostgreSQL模式匹配的方法 LIKE等
			
PostgreSQL 提供了三种实现模式匹配的方法:传统 SQL 的 LIKE 操作符.SQL99 新增的 SIMILAR TO 操作符. POSIX 风格的正则表达式.另外还有一个模式匹配函数 su ...
 - iOS判断当前时间是否处于某个时间段内
			
/** * 判断当前时间是否处于某个时间段内 * * @param startTime 开始时间 * @param expireTime 结束时间 */ - (BOOL)validateWithSta ...
 - 【Python】Camera拍照休眠唤醒测试
			
#!/usr/bin/python # -*- coding: UTF-8 -*- import os import sys import time rebootCount = int(input(& ...
 - iOS 监听控件某个属性的改变observeValueForKeyPath
			
创建一个测试的UIButton #import "ViewController.h" @interface ViewController () @property(nonatomi ...
 - Java中动态代理技术生成的类与原始类的区别 (good)
			
用动态代理的时候,对它新生成的类长什么样子感到好奇.有幸通过一些资料消除了心里的疑惑. 平时工作使用的Spring框架里面有一个AOP(面向切面)的机制,只知道它是把类重新生成了一遍,在切面上加上了后 ...
 - ArcGIS for Desktop入门教程_第一章_引言 - ArcGIS知乎-新一代ArcGIS问答社区
			
原文:ArcGIS for Desktop入门教程_第一章_引言 - ArcGIS知乎-新一代ArcGIS问答社区 1 引言 1.1 读者定位 我们假设用户在阅读本指南前应已具备以下知识: · 熟悉W ...