a.ArrayList源码解析(1.7)
来源:互联网 发布:mac快速进入屏保 编辑:程序博客网 时间:2024/06/06 04:46
工作有几年了,终于有时间静下心来对自己这些年一直都在用的一些技术做一些整理,总结,算是对过去有个交代,也对明天做个准备
作为集合源码系列的第一篇,也以此对以后源码的分析做一个规则,我会依次按照 属性,构造方法,方法,内部类 四个模块去做解析
首先从他的类名来看,他实现了List接口,并且继承了抽象List,同时可以做克隆
属性
初始容量private static final int DEFAULT_CAPACITY = 10;
final的空数组
private static final Object[] EMPTY_ELEMENTDATA = {};
存放元素的数组
private transient Object[] elementData;
数组大小
private INTsize;
计数器
protected transient int modCount = 0;
构造方法
//定义初始容量
public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; }//没有参数,则赋值成为空数组,所有对象统一是同一个 public ArrayList() { super(); this.elementData = EMPTY_ELEMENTDATA; } //参数为集合,依次加入 public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); }
方法
add
/** * 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}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
private void ensureCapacityInternal(int minCapacity) { if (elementData == EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }
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); }
代码写的比较清楚,当size+1大于原来数组的elementData.length,即扩容,扩容是原来的二分之一
有个点是modCount++,亦即数组操作数加一。在后面碰到会进行解释
public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! System.arraycopy(elementData, index, elementData, index + 1, size - index); elementData[index] = element; size++; }
首先查看是否越界,否则报错
其次保证新增之后扩容检查
再次把index开始的元素后移
最后把elementData【index】赋值
public boolean addAll(Collection<? extends E> c) { Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount System.arraycopy(a, 0, elementData, size, numNew); size += numNew; return numNew != 0; }
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) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; }
跟单体add区别不大,只不过需要先把集合转换成数组,然后对数组进行插入
Object[] a = c.toArray(); int numNew = a.length;
clear
public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; }数组空间不释放,只是把引用置为null,size置为0,另外操作数加一
remove
public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; }
public boolean remove(Object o) { 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])) { fastRemove(index); return true; } } return false; } /* * Private remove method that skips bounds checking and does not * return the value removed. */ private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
remove大概分两种,remove(Object)也是通过遍历获取index,然后才用数组移动的方式类似于remove(index)
lastindexof
public int lastIndexOf(Object o) { if (o == null) { 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; }没太多好说的,倒着遍历即可
isEmpty
直接通过size返回值
indexOf
过于简单不再赘述
rangecheck
不再赘述
get
不再赘述
contails
通过indexof实现
还有一个比较重要的点,也就是迭代器,虽然我们已经习惯了用foreach循环,但是本质上foreach也是用iterator实现的。迭代器本身的remove实现也可以解释为什么迭代器迭代器在迭代的时候可以删除元素,但是普通的foreach不可以
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 int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
0 0
- a.ArrayList源码解析(1.7)
- ArrayList 源码解析
- ArrayList源码解析
- android源码解析 -- ArrayList
- ArrayList源码解析
- ArrayList源码解析
- ArrayList源码解析
- ArrayList源码解析
- ArrayList LinkedList源码解析
- ArrayList 源码解析
- ArrayList集合源码解析
- ArrayList源码解析
- ArrayList类源码解析
- ArrayList源码解析
- ArrayList源码解析
- ArrayList 部分源码解析
- ArrayList源码解析
- ArrayList源码解析
- linux内核参数tcp_syn_retries、tcp_retries1和tcp_retries2的源码分析
- leetcode-33-search in rotated array
- C#制作WinForm控件
- 混淆Android代码
- 给activity设置自定义权限
- a.ArrayList源码解析(1.7)
- 欢迎使用CSDN-markdown编辑器
- Typhon升级到5.8,编译原来程序出现提示:Compilation raised exception internally
- 人件读书笔记(20)人力资本
- 手动创建XIB文件
- centos6.7安装redis3.2.3
- iar "exclude from build"
- android多线程数据存储 - ThreadLocal的工作原理
- HHUOJ 1005 内部收益率 (二分法求方程解)