这是博主第二次读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&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;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集合 源码阅读的更多相关文章

  1. java1.7集合源码阅读: Stack

    Stack类也是List接口的一种实现,也是一个有着非常长历史的实现,从jdk1.0开始就有了这个实现. Stack是一种基于后进先出队列的实现(last-in-first-out (LIFO)),实 ...

  2. java1.7集合源码阅读: Vector

    Vector是List接口的另一实现,有非常长的历史了,从jdk1.0开始就有Vector了,先于ArrayList出现,与ArrayList的最大区别是:Vector 是线程安全的,简单浏览一下Ve ...

  3. 【JDK1.8】JDK1.8集合源码阅读——IdentityHashMap

    一.前言 今天我们来看一下本次集合源码阅读里的最后一个Map--IdentityHashMap.这个Map之所以放在最后是因为它用到的情况最少,也相较于其他的map来说比较特殊.就笔者来说,到目前为止 ...

  4. 【JDK1.8】JDK1.8集合源码阅读——ArrayList

    一.前言 在前面几篇,我们已经学习了常见了Map,下面开始阅读实现Collection接口的常见的实现类.在有了之前源码的铺垫之后,我们后面的阅读之路将会变得简单很多,因为很多Collection的结 ...

  5. JDK 1.8源码阅读 ArrayList

    一,前言 ArrayList是Java开发中使用比较频繁的一个类,通过对源码的解读,可以了解ArrayList的内部结构以及实现方法,清楚它的优缺点,以便我们在编程时灵活运用. 二,ArrayList ...

  6. 【JDK1.8】JDK1.8集合源码阅读——总章

    一.前言 今天开始阅读jdk1.8的集合部分,平时在写项目的时候,用到的最多的部分可能就是Java的集合框架,通过阅读集合框架源码,了解其内部的数据结构实现,能够深入理解各个集合的性能特性,并且能够帮 ...

  7. 【JDK1.8】JDK1.8集合源码阅读——HashMap

    一.前言 笔者之前看过一篇关于jdk1.8的HashMap源码分析,作者对里面的解读很到位,将代码里关键的地方都说了一遍,值得推荐.笔者也会顺着他的顺序来阅读一遍,除了基础的方法外,添加了其他补充内容 ...

  8. 【JDK1.8】JDK1.8集合源码阅读——LinkedList

    一.前言 这次我们来看一下常见的List中的第二个--LinkedList,在前面分析ArrayList的时候,我们提到,LinkedList是链表的结构,其实它跟我们在分析map的时候讲到的Link ...

  9. JDK 1.8源码阅读 TreeMap

    一,前言 TreeMap:基于红黑树实现的,TreeMap是有序的. 二,TreeMap结构 2.1 红黑树结构 红黑树又称红-黑二叉树,它首先是一颗二叉树,它具体二叉树所有的特性.同时红黑树更是一颗 ...

随机推荐

  1. 奥格尔巧妙kfifo

    奥格尔巧妙kfifo Author:Echo Chen(陈斌) Email:chenb19870707@gmail.com Blog:Blog.csdn.net/chen19870707 Date:O ...

  2. mybatis 使用经验小结 good

    一.多数据源问题 主要思路是把dataSource.sqlSesstionFactory(用来产生sqlSession).MapperScannerConfigurer在配置中区分开,各Mapper对 ...

  3. Notepad++ 自定义关键字

    Notepad++是一款輕便好用的編輯器,但可能有些語言的關鍵字不全,比方SQL中,默認關鍵字沒有Merge. 怎样給Notepad++中的語言添加關鍵字,而不是大動干戈自定義一個語言? 步驟: Se ...

  4. 基于Android开发的天气预报app(源码下载)

    原文:基于Android开发的天气预报app(源码下载) 基于AndroidStudio环境开发的天气app -系统总体介绍:本天气app使用AndroidStudio这个IDE工具在Windows1 ...

  5. Effective C++:规定24:如果所有的单位都需要的参数类型转换,使用请做到这一点non-member功能

    (一个) 如果一个class.同意整数"隐式转换为"有理数似乎非常合理. class Rational{ public: Rational(int numerator = 0, i ...

  6. 推荐几个js的好链接

    JavaScript 之美 其一:http://fxck.it/post/72326363595 其二:http://fxck.it/post/73513189448

  7. vagrant up default: Warning: Authentication failure. Retrying...的一些解决办法

    vagrant up default: Warning: Authentication failure. Retrying...的一些解决办法 一般看到这个信息时,虚拟机已经启动成功,可以中断命令后v ...

  8. Logback 专题

    logback-spring.xml <?xml version="1.0" encoding="UTF-8"?> <configuratio ...

  9. IOS开发之关于NSString和NSMutableString的retainCount

    1. 字符串常量 NSString *s = @"test"; NSLog(@"s:%lx",[s retainCount]); //fffffffffffff ...

  10. n阶贝塞尔曲线绘制(C/C#)

    原文:n阶贝塞尔曲线绘制(C/C#) 贝塞尔是很经典的东西,轮子应该有很多的.求n阶贝塞尔曲线用到了 德卡斯特里奥算法(De Casteljau's Algorithm) 需要拷贝代码请直接使用本文最 ...