java数据结构 ArrayList源码阅读
来源:互联网 发布:数据猿 百度百科 编辑:程序博客网 时间:2024/06/05 00:46
ArrayList 数据结构
ArrayList的底层实现方式就是数组,在操作过程中进行动态扩容,来满足数组内容增加而导致的数组长度不足导致的溢出问题
ArrayList特性
1.随机访问速度快,插入和移除性能较差(数组的特点);
2.支持null元素;
3.有顺序;
4.元素可以重复;
5.线程不安全;
ArrayList 数组中的transient
transient Object[] elementData;
java里面关键字transient所标记的对象是不能被序列化的,那么ArrayList的序列化怎么解决呢?
思考:如果我们序列化的时候每次都将完整的整个数组序列化到流中或者反序列化性能肯定不会很好。所以为了提升性能ArrayList中只将数组中实际存在的元素序列化。(由于自动扩容机制导致有部分空间未使用,所以序列化的时候不需要考虑)
(1)ArrayList序列化:
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // 保存对象写入前的对象修改值modCount是内存可见的 int expectedModCount = modCount; s.defaultWriteObject(); // 将数组的真实大小写入流中 s.writeInt(size); // 遍历写入elementData中已利用空间的对象 for (int i=0; i<size; i++) { s.writeObject(elementData[i]); } //如果并发情况下序列化后发现又被修改了则抛出异常 if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } }
(2)ArrayList反序列化
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { elementData = EMPTY_ELEMENTDATA; // Read in size, and any hidden stuff s.defaultReadObject(); // 从对象中读取size s.readInt(); // ignored if (size > 0) { // 计算并分配存储空间 ensureCapacityInternal(size); Object[] a = elementData; //从流中读取并遍历写入到.elementData for (int i=0; i<size; i++) { a[i] = s.readObject(); } } }
虽然transient对象不能序列化但是我们可以取出来在序列化,这样就没必要将多余的空间序列化增加 IO 的开销。
ArrayList 如何动态扩容?
(1)ArrayList的构造方法:
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); } } /** * Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
(2)当我们在创建一个List list=new ArrayList()时执行上面的构造方法,次构造方法默认给elementData 给了一个空数组。
(3)当执行list.add(“zhangsan”)时候会进行存储空间是否满足需求的确认。
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
- add函数会调用ensureCapacityInternal方法,将数组原来的大小增加1传入该方法。
- ensureCapacityInternal方法,并比较传入的参数与默认DEFAULT_CAPACITY的大小,取其中最大的值
private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); }
- 接着 调用ensureExplicitCapacity方法
private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }
首先数组的操作次数加一,如果最小容量大于当前的数组的容量则进行扩容操作,调用grow方法。
4. grow扩容
private void grow(int minCapacity) { // 保存原来的数组长度 int oldCapacity = elementData.length; //新数组长度扩大为原来的数组的1.5倍 int newCapacity = oldCapacity + (oldCapacity >> 1); //如果扩容后的数组大小还是不满足则新数组的大小就等于需要的大小 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; //如果新数组的大小减去MAX_ARRAY_SIZE ( Integer.MAX_VALUE - 8;最大值减8).则调用hugeCapacity方法 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) { //如果要大小小于0抛出异常 if (minCapacity < 0) // overflow throw new OutOfMemoryError();//需要的容量大于int最大值减8则返回最大值,否则就返回int最大值减8 return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }
- 扩容好了就需要复制数组到新的数组里面去了
elementData = Arrays.copyOf(elementData, newCapacity);实际调用的以下方法
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { @SuppressWarnings("unchecked") T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }
ArrayList 添加元素
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
第一种方法直接进行容量确认,如有必要进行扩容等,然后直接将数据添加到指定的位置就完成了。
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++; }
第二种则是在指定的位置进行插入操作,此时需要大量的移动数组System.arraycopy(elementData, index, elementData, index + 1,
size - index);插入位置index以及后面的所有元素往后移动最后在index位置插入元素
ArrayList 删除元素
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 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 }
根据对象移除元素,如有重复元素先移除最近的元素然后将后面的数组前移。如果我们需要找出list里面某一个元素并且移除他,这时随着你移除元素list的大小也跟着改变了。通过大小来一边遍历一边移除数组就会存在问题。
ArrayList的迭代器Iterator
如果在循环的过程中调用集合的remove()方法,就会导致循环出错,因为循环过程中list.size()的大小变化了,就导致了错误。 所以,如果想在循环语句中删除集合中的某个元素,就要用迭代器iterator的remove()方法,因为它的remove()方法不仅会删除元素,还会维护一个标志,用来记录目前是不是可删除状态,例如,你不能连续两次调用它的remove()方法,调用之前至少有一次next()方法的调用
private class Itr implements Iterator<E> { /** * Index of element to be returned by subsequent call to next. */ int cursor = 0; /** * Index of element returned by most recent call to next or * previous. Reset to -1 if this element is deleted by a call * to remove. */ int lastRet = -1; /** * The modCount value that the iterator believes that the backing * List should have. If this expectation is violated, the iterator * has detected concurrent modification. */ int expectedModCount = modCount; public boolean hasNext() { return cursor != size(); } public E next() { checkForComodification(); try { int i = cursor; E next = get(i); lastRet = i; cursor = i + 1; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
Iterator相当于一个类似游标的东西,可以双向移动,通过它我们可以遍历list集合.
例如:
Iterator it1 = list.iterator(); while(it1.hasNext()){ System.out.println(it1.next()); }
- java数据结构 ArrayList源码阅读
- Java源码阅读-ArrayList
- Java源码阅读-ArrayList
- Java源码阅读之ArrayList
- Java源码阅读之ArrayList
- Java源码阅读之ArrayList
- java源码阅读系列-ArrayList
- java 数据结构. 源码阅读
- Java数据结构源码分析-ArrayList
- Java数据结构 HashMap 源码阅读
- ArrayList源码阅读笔记
- ArrayList源码阅读
- ArrayList源码阅读
- java8 ArrayList源码阅读
- 源码阅读之ArrayList
- ArrayList源码阅读
- ArrayList源码阅读笔记
- ArrayList源码阅读
- LCD及FrameBuffer驱动(二)-------------------FrameBuffer
- Hibernate实体类中包含另一个实体类
- Java命名规范
- 编程之美-2.17 数组移位循环
- Ubuntu安装Composer
- java数据结构 ArrayList源码阅读
- Python 数据分析包:pandas 基础
- 猎头面试17年4月20日
- BZOJ 3681: Arietta
- libsvm的使用
- 51nod1003
- 纯CSS3实现不错的表单验证效果
- soy文件的语法规则
- C语言函数传递指针参数的问题