Java 集合(1)----- ArrayList 源码分析
来源:互联网 发布:mac ssh免密码登录 编辑:程序博客网 时间:2024/06/08 08:15
ArrayList
Java Collection系列博客分析了我们日常使用过程中常用集合的常用方法源码
在阅读源码过程中遇到了一个问题, System.arraycopy()到底是怎么拷贝的?深拷贝还是浅拷贝? 根据实验的结果对基本数据类型是深拷贝,class对象是浅拷贝,根据网上各种博客加上个人的理解最后确认了System.arraycopy()就是浅拷贝,深拷贝是浅拷贝的递归
测试代码地址http://blog.csdn.net/chenqianleo/article/details/77480407
ArrayList继承的类和接口
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, ,Cloneable,1. RandomAccess,Cloneable,java.io.Serializable三个都是标识接口,标识接口内部没有任何东西,仅仅起到标识的作用2. List<E> ArrayList<E>中的大部分方法都是从List<E>接口继承过来的 List<E> -->Collection<E> -->Iterable<E>3. AbstractList<E> 一直往上看可以发现继承了Iterable接口 AbstractList<E> --> AbstractCollection<E> --> Collection<E> -->Iterable<E>
主要成员变量
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //空数组,在无参构造函数使用private static final Object[] EMPTY_ELEMENTDATA = {}; //空数组,在初始化容量指定为0时使用,和使用无参构造方法一个作用private static final int DEFAULT_CAPACITY = 10; //初始数组大小transient Object[] elementData; //数据用数组保存private int size; //当前数组存入数据大小,很重要protected transient int modCount = 0; //ArrayList结构性变化的次数
1.构造函数
/** * 无参构造函数 * 这个构造函数我们一般使用的比较多,在初始化时并没有建立数组,在add才会 */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * @Parm initialCapacity为指定数组容量大小 * 初始化时进行了数组大小的确定,一般我们知道数据量大小时可以这样使用,减小后面的数组扩容 */ public ArrayList(int initialCapacity) { if (initialCapacity > 0) { this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { this.elementData = EMPTY_ELEMENTDATA; //还是初始化为{}数组 } else { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } /** * @Parm c 集合 * 集合中的内容全部填充到数组中 */ public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) (英文注释都是SDK自带的) 类型转换 if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // replace with empty array. this.elementData = EMPTY_ELEMENTDATA; } }
2.主要方法
add(E e) –> 插入元素到数组末尾
把对象存储到动态数组中,每次存储前会进行ensureCapacityInternal()(具体判断在ensureExplicitCapacity())确保当前数组大小可以存储数据,当数组容量不够存储数据时进行扩容grow(),扩容的大小为指定大小和原大小1.5倍的最大值
下面的所以add方法原理都很简单,主要有下面几点
1.add前容量判断
2.中间index位置插入元素,index及其后面所以成员后移,要插入的元素直接从index位置连续插入
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! //正常数组操作,size为已经存储的数据大小 elementData[size++] = e; return true; } //确保数组容量,不满足时扩容 private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { //如何当前数组为空,选择传入参数minCapacity和DEFAULT_CAPACITY==10之间的最大值作为扩容目标 minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } // //进行扩容 private void ensureExplicitCapacity(int minCapacity) { modCount++; //扩容次数++ // overflow-conscious code //大小判断,如果当前数组容量大于minCapacity什么都不做,否则进行扩容操作 if (minCapacity - elementData.length > 0) grow(minCapacity); } //扩容操作 private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; //以前容量 int newCapacity = oldCapacity + (oldCapacity >> 1); //新容量 = 以前容量 * 1.5 //在自动扩容1.5倍和指定扩容大小选最大的 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) //容量大小最大为Integer.MAX_VALUE newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: //System.arraycopy()完成数据的拷贝,JNI实现; elementData = Arrays.copyOf(elementData, newCapacity); }
add(int index, E element) –> 插入元素到指定位置(不建议这样,当插入操作频繁建议使用LinkList)
public void add(int index, E element) { rangeCheckForAdd(index); //插入位置边界检查 //容量判断,上面分析了 ensureCapacityInternal(size + 1); // Increments modCount!! //先把插入位置index及其后面的数据往后移动一位 System.arraycopy(elementData, index, elementData, index + 1, size - index); //再把数据放到index位置 elementData[index] = element; size++; } //确保要插入的位置在数组已有数据大小0-size之间,否则抛出异常 private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
addAll(Collection c) –> 集合c中的全部数据加到数组末尾
public boolean addAll(Collection<? extends E> c) { //集合c转换成数组 Object[] a = c.toArray(); int numNew = a.length; //确保当前容量可以增加集合c的大小 ensureCapacityInternal(size + numNew); // Increments modCount //把集合c转换的数组a加入到elementData数组的后面 System.arraycopy(a, 0, elementData, size, numNew); //数据容量加上集合大小 size += numNew; return numNew != 0; }
addAll(int index, Collection c) –> 集合插入指定位置
public boolean addAll(int index, Collection<? extends E> c) { rangeCheckForAdd(index); //插入位置边界检查 //集合转数据 Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount int numMoved = size - index; if (numMoved > 0) //index和后面的数据向后移动集合c大小各位置 System.arraycopy(elementData, index, elementData, index + numNew, numMoved); //集合转的数组从index依次插入 System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; }
clear() –> 清空数据
public void clear() { modCount++; //扩容次数加加 // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; //变量不在使用时让他==null,触发gc size = 0; }
size() –> 得到当前存入数据数量
isEmpty() –> 当前是否存入数据
public int size() { return size; //直接返回size } public boolean isEmpty() { return size == 0; //还是通过size判断 }
clone() –> 得到一份浅拷贝
public Object clone() { try { ArrayList<?> v = (ArrayList<?>) super.clone(); //浅拷贝 v.elementData = Arrays.copyOf(elementData, size); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } }
toArray() –> 集合转数组
public Object[] toArray() { //仍然是使用浅拷贝的Arrays.copyOf方法 return Arrays.copyOf(elementData, size); }
remove(int index) –> 移除index位置的元素
public E remove(int index) { rangeCheck(index); //index边界检查 modCount++; //return (E) elementData[index] 得到index位置数据 E oldValue = elementData(index); int numMoved = size - index - 1; //index后面元素向前移动一位 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work //返回index位置的数据 return oldValue; }
remove(Object o) –> 删除第一次出现的指定元素从这个列表,如果它存在
public boolean remove(Object o) { //从数组0位置开始查找,针对null和其他元素的比较方法不一样 if (o == null) { //== for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); //移除数据 return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { // equal fastRemove(index); return true; } } return false; } private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; //index后面前移一位覆盖了index原来数据 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
indexOf(Object 0) –> 回第一次出现的指定元素的索引列表,或-1如果该列表不包含的元素。
public int indexOf(Object o) { if (o == null) { //循环判断进行比较,如果找到返回i for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; }
lastIndexOf(Object o) – > 返回最后出现的指定元素的索引列表,或1如果该列表不包含的元素。
public int lastIndexOf(Object o) { if (o == null) { //和上面一样,不过这个数组从size-1到0进行遍历 for (int i = size-1; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = size-1; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; }
下面简单分析一下ArrayList中的Iterator,从ArrayList的listIterator()方法作为入口进行分析
public ListIterator<E> listIterator() { return new ListItr(0); //接下来主要分析ListItr内部类 }
private class ListItr extends Itr implements ListIterator
- Itr 实现了也是ArrayList的一个内部类,实现了主要的几个部分
- ListIterator是一个外部接口
Itr类,只分析常用的hasNext()和next()方法
private class Itr implements Iterator<E> { int cursor; // index of next element to return,很重要的 int lastRet = -1; // index of last element returned; -1 if no such //这个大家都很熟悉吧,判断下个元素是否存在,原理很简单 //当前的索引cursor是否等于数组存储的数据大小size public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); //当前的cursor索引不可以大于等于size,为什么等于?因为后面使用cursor前cursor要加1 int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; //cursor加加,代表下一个元素索引 return (E) elementData[lastRet = i]; //返回元素 } //删除上次遍历的cursor索引所在的元素 public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); //删除cursor所在数据 try { ArrayList.this.remove(lastRet); cursor = lastRet; //----->删除后设为-1,所以不能连续删除<----// lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } }
ListItr,最重要的成员变量是继承Itr的cursor
private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } //判断当前cursor所以是否前一个 public boolean hasPrevious() { return cursor != 0; } //返回前一个元素 public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; } }
最后,Vector暂时不打算分析了,Vector中大部分方法用synchronized修饰,动态数组的原理和ArrayList相似,下一篇打算分析HashSet
- Java 集合(1)----- ArrayList 源码分析
- java集合(2):ArrayList源码分析
- Java集合-ArrayList源码分析
- 【java集合】ArrayList源码分析
- Java集合源码分析系列-(一)ArrayList源码剖析
- Java集合框架(2)—ArrayList源码分析
- java 中的集合(三) ArrayList源码分析
- Java集合源码学习(二)ArrayList分析
- java 集合ArrayList及LinkList源码分析
- Java集合框架源码分析之ArrayList
- java 集合ArrayList及LinkList源码分析
- 从源码分析java集合【ArrayList】
- Java集合系列之ArrayList源码分析
- java 集合ArrayList及LinkList源码分析
- java集合03--ArrayList源码分析
- java集合03--ArrayList源码分析
- Java集合源码分析之ArrayList
- java 集合ArrayList及LinkList源码分析
- Python打印斐波那契数列
- Monkey详解(限制型指令篇)
- Apache Spark探秘:多进程模型还是多线程模型?
- Linux 杀死某个用户的所有进程
- 关于logging.DEBUG 很好的讲解
- Java 集合(1)----- ArrayList 源码分析
- 孙源的Runloop视频整理
- 玩转Markdown
- HashMap和Hashtable的区别
- UIButton 扩大点击区域
- Java实现邮箱验证
- [Linux]使用awk批量杀进程的命令
- 【广告算法工程师入门 0】开篇语:显然,我不是搬砖的料
- Python倒序输出并统计位数