Java-ArrayList源码分析及示例

纸上得来终觉浅,绝知此事要躬行
 --陆游    
问渠那得清如许,为有源头活水来  --朱熹

ArrayList简介:ArrayList是一个数组队列,相当于一个动态的数组,容量可以动态的增长;它继承了AbstractList并实现了List,RandomAccess,Cloneable、Serializable这些接口。

特性:

(1)ArrayList继承了AbstractList,实现了List,它是一个数组队列,提供了相关的添加、删除、修改、遍历等功能。

(2)ArrayList实现了RandomAccess接口,提供了随机访问功能,RandomAccess是Java中用来被List实现,为List提供快速访问功能的;还可以通过元素下标进行快速随机访问。

(3)ArrayList实现了Cloneable接口,覆盖了函数clone(),可以被克隆。

(4)ArrayList实现了Serializable接口,可以被序列化,通过网络传输。

(5)ArrayList不是线程安全的,建议在单线程中使用。

(6)ArrayList是使用elementData一个Object[] 数组来动态存储数据的。

ArrayList支持三种遍历方式:

(1)通过迭代器进行遍历,即通过Itreator去遍历

Integer value=null;Iterator iter=list.iterator();while(iter.hasNext()){    value=(Interger)iter.next();}

(2)随机访问模式,通过索引值去遍历所有元素

Interger value=null;int size=list.size();fo(int i=0;i<size;i++){    value=(Integer)list.get(i);}

(3)for循环遍历

Integer value=null;for(Integer inte : list){    value=inte;}

三种遍历方式中通过索引去遍历速度最快,通过迭代器去遍历速度最慢。

示例程序:

public class Hello {

public static void main(String[] args) {

ArrayList list = new ArrayList();list.add("1");list.add("2");list.add("3");list.add("4");list.add(0, "5");System.out.println("the first element is: "+ list.get(0));list.remove("3");System.out.println("Arraylist size=: "+ list.size());System.out.println("ArrayList contains 3 is: "+ list.contains(3));list.set(1, "10");        for(Iterator iter = list.iterator(); iter.hasNext(); )        {            System.out.println("next is: "+ iter.next());}        String[] arr = (String[])list.toArray(new String[0]);        for (String str:arr)            System.out.println("str: "+ str);list.clear();System.out.println("ArrayList is empty: "+ list.isEmpty());}}

运行结果:

the first element is: 5

Arraylist size=: 4

ArrayList contains 3 is: false

next is: 5

next is: 10

next is: 2

next is: 4

str: 5

str: 10

str: 2

str: 4

ArrayList is empty: true

ArrayList源代码分析:

// Arraylist继承了AbstractList 实现了List,RandomAccess,Cloneable,Serializable接口

public class ArrayList<E> extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable{private static final long serialVersionUID = 8683452581122892189L;  //序列化IDprivate static final int DEFAULT_CAPACITY = 10; //初始大小为10,会动态增加private static final Object[] EMPTY_ELEMENTDATA = {};//空的数组实例private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};    transient Object[] elementData; // ArrayList用来存储对象的数组private int size;//数组中包含对象的个数//ArrayList构造函数,构造初始大小的elementDatapublic 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);}    }//构造函数,初始化大小为10的数组public ArrayList() {this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}//带有Collection的构造函数public ArrayList(Collection<? extends E> c) {elementData = c.toArray();        if ((size = elementData.length) != 0) {// c.toArray might (incorrectly) not return Object[] (see 6260652)if (elementData.getClass() != Object[].class)elementData = Arrays.copyOf(elementData, size, Object[].class);} else {// replace with empty array.this.elementData = EMPTY_ELEMENTDATA;}    }//当前容量值设置为实际个数public void trimToSize() {        modCount++;        if (size < elementData.length) {elementData = (size == 0)                    ? EMPTY_ELEMENTDATA: Arrays.copyOf(elementData, size);}    }//判断容量,容量不够增加public void ensureCapacity(int minCapacity) {int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)// any size if not default element table? 0// larger than default for default empty table. It‘s already                // supposed to be at default size.: DEFAULT_CAPACITY;

if (minCapacity > minExpand) {            ensureExplicitCapacity(minCapacity);}    }private void ensureCapacityInternal(int minCapacity) {if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);}

ensureExplicitCapacity(minCapacity);}

private void ensureExplicitCapacity(int minCapacity) {        modCount++;

// overflow-conscious codeif (minCapacity - elementData.length > 0)            grow(minCapacity);}//最大的容量分配private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;    private void grow(int minCapacity) {// overflow-conscious codeint 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) {if (minCapacity < 0) // overflowthrow new OutOfMemoryError();        return (minCapacity > MAX_ARRAY_SIZE) ?                Integer.MAX_VALUE :MAX_ARRAY_SIZE;}//返回ArrayList的大小public int size() {return size;}//判断ArrayList是否为空public boolean isEmpty() {return size == 0;}//判断是否含有某个对象public boolean contains(Object o) {return indexOf(o) >= 0;}//查找对象,返回坐标public int indexOf(Object o) {if (o == null) {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;}//返回对象相同的最后一个坐标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;}//返回一个影子对象克隆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 Cloneablethrow new InternalError(e);}    }//返回一个包含所有ArrayList元素的数组public Object[] toArray() {return Arrays.copyOf(elementData, size);}//返回泛型对象数组,一般使用这个不是上边那个@SuppressWarnings("unchecked")public <T> T[] toArray(T[] a) {if (a.length < size)// Make a new array of a‘s runtime type, but my contents:return (T[]) Arrays.copyOf(elementData, size, a.getClass());System.arraycopy(elementData, 0, a, 0, size);        if (a.length > size)            a[size] = null;        return a;}//得到指定下标的对象@SuppressWarnings("unchecked")E elementData(int index) {return (E) elementData[index];}//得到指定下标的对象,并对下标进行判断public E get(int index) {        rangeCheck(index);

return elementData(index);}//替换指定下标的对象,会检查下标并返回public E set(int index, E element) {        rangeCheck(index);

E oldValue = elementData(index);elementData[index] = element;        return oldValue;}//追加对象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++;}//删除指定坐标的对象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;}// 删除ArrayList第一次出现的对象opublic 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}//清空ArrayListpublic void clear() {        modCount++;

// clear to let GC do its workfor (int i = 0; i < size; i++)elementData[i] = null;

size = 0;}//将集合C追加到ArrayList中public boolean addAll(Collection<? extends E> c) {        Object[] a = c.toArray();        int numNew = a.length;ensureCapacityInternal(size + numNew);  // Increments modCountSystem.arraycopy(a, 0, elementData, size, numNew);size += numNew;        return numNew != 0;}//在ArrayList中的某个坐标后追加集合cpublic boolean addAll(int index, Collection<? extends E> c) {        rangeCheckForAdd(index);

Object[] a = c.toArray();        int numNew = a.length;ensureCapacityInternal(size + numNew);  // Increments modCountint 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;}//删除范围中的对象protected void removeRange(int fromIndex, int toIndex) {        modCount++;        int numMoved = size - toIndex;System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);

// clear to let GC do its workint newSize = size - (toIndex-fromIndex);        for (int i = newSize; i < size; i++) {elementData[i] = null;}size = newSize;}//范围检查private void rangeCheck(int index) {if (index >= size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}//在添加或者添加所有的时候范围检查private void rangeCheckForAdd(int index) {if (index > size || index < 0)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}private String outOfBoundsMsg(int index) {return "Index: "+index+", Size: "+size;}public boolean removeAll(Collection<?> c) {        Objects.requireNonNull(c);        return batchRemove(c, false);}public boolean retainAll(Collection<?> c) {        Objects.requireNonNull(c);        return batchRemove(c, true);}//删除c中的在ArrayList中存在或者不存在的private boolean batchRemove(Collection<?> c, boolean complement) {final Object[] elementData = this.elementData;        int r = 0, w = 0;        boolean modified = false;        try {for (; r < size; r++)if (c.contains(elementData[r]) == complement)                    elementData[w++] = elementData[r];} finally {// Preserve behavioral compatibility with AbstractCollection,            // even if c.contains() throws.if (r != size) {                System.arraycopy(elementData, r,elementData, w,size - r);w += size - r;}if (w != size) {// clear to let GC do its workfor (int i = w; i < size; i++)                    elementData[i] = null;modCount += size - w;size = w;modified = true;}        }return modified;}//序列化private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException{// Write out element count, and any hidden stuffint expectedModCount = modCount;s.defaultWriteObject();

// Write out size as capacity for behavioural compatibility with clone()s.writeInt(size);

// Write out all elements in the proper order.for (int i=0; i<size; i++) {            s.writeObject(elementData[i]);}

if (modCount != expectedModCount) {throw new ConcurrentModificationException();}    }//反序列化private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {elementData = EMPTY_ELEMENTDATA;// Read in size, and any hidden stuffs.defaultReadObject();// Read in capacitys.readInt(); // ignoredif (size > 0) {// be like clone(), allocate array based upon size not capacityensureCapacityInternal(size);Object[] a = elementData;// Read in all elements in the proper order.for (int i=0; i<size; i++) {                a[i] = s.readObject();}        }    }

public ListIterator<E> listIterator(int index) {if (index < 0 || index > size)throw new IndexOutOfBoundsException("Index: "+index);        return new ListItr(index);}public ListIterator<E> listIterator() {return new ListItr(0);}public Iterator<E> iterator() {return new Itr();}private class Itr implements Iterator<E> {int cursor;       // index of next element to returnint lastRet = -1; // index of last element returned; -1 if no suchint 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();}        }

@Override        @SuppressWarnings("unchecked")public void forEachRemaining(Consumer<? super E> consumer) {            Objects.requireNonNull(consumer);            final int size = ArrayList.this.size;            int i = cursor;            if (i >= size) {return;}final Object[] elementData = ArrayList.this.elementData;            if (i >= elementData.length) {throw new ConcurrentModificationException();}while (i != size && modCount == expectedModCount) {                consumer.accept((E) elementData[i++]);}// update once at end of iteration to reduce heap write trafficcursor = i;lastRet = i - 1;checkForComodification();}

final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}    }private class ListItr extends Itr implements ListIterator<E> {        ListItr(int index) {super();cursor = index;}

public boolean hasPrevious() {return cursor != 0;}

public int nextIndex() {return cursor;}

public int previousIndex() {return cursor - 1;}

@SuppressWarnings("unchecked")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];}

public void set(E e) {if (lastRet < 0)throw new IllegalStateException();checkForComodification();

try {                ArrayList.this.set(lastRet, e);} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}        }

public void add(E e) {            checkForComodification();

try {int i = cursor;ArrayList.this.add(i, e);cursor = i + 1;lastRet = -1;expectedModCount = modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}        }    }public List<E> subList(int fromIndex, int toIndex) {subListRangeCheck(fromIndex, toIndex, size);        return new SubList(this, 0, fromIndex, toIndex);}

static void subListRangeCheck(int fromIndex, int toIndex, int size) {if (fromIndex < 0)throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);        if (toIndex > size)throw new IndexOutOfBoundsException("toIndex = " + toIndex);        if (fromIndex > toIndex)throw new IllegalArgumentException("fromIndex(" + fromIndex +") > toIndex(" + toIndex + ")");}

private class SubList extends AbstractList<E> implements RandomAccess {private final AbstractList<E> parent;        private final int parentOffset;        private final int offset;        int size;

SubList(AbstractList<E> parent,                int offset, int fromIndex, int toIndex) {this.parent = parent;            this.parentOffset = fromIndex;            this.offset = offset + fromIndex;            this.size = toIndex - fromIndex;            this.modCount = ArrayList.this.modCount;}

public E set(int index, E e) {            rangeCheck(index);checkForComodification();E oldValue = ArrayList.this.elementData(offset + index);ArrayList.this.elementData[offset + index] = e;            return oldValue;}

public E get(int index) {            rangeCheck(index);checkForComodification();            return ArrayList.this.elementData(offset + index);}

public int size() {            checkForComodification();            return this.size;}

public void add(int index, E e) {            rangeCheckForAdd(index);checkForComodification();parent.add(parentOffset + index, e);            this.modCount = parent.modCount;            this.size++;}

public E remove(int index) {            rangeCheck(index);checkForComodification();E result = parent.remove(parentOffset + index);            this.modCount = parent.modCount;            this.size--;            return result;}

protected void removeRange(int fromIndex, int toIndex) {            checkForComodification();parent.removeRange(parentOffset + fromIndex,parentOffset + toIndex);            this.modCount = parent.modCount;            this.size -= toIndex - fromIndex;}

public boolean addAll(Collection<? extends E> c) {return addAll(this.size, c);}

public boolean addAll(int index, Collection<? extends E> c) {            rangeCheckForAdd(index);            int cSize = c.size();            if (cSize==0)return false;

checkForComodification();parent.addAll(parentOffset + index, c);            this.modCount = parent.modCount;            this.size += cSize;            return true;}

public Iterator<E> iterator() {return listIterator();}

public ListIterator<E> listIterator(final int index) {            checkForComodification();rangeCheckForAdd(index);            final int offset = this.offset;

return new ListIterator<E>() {int cursor = index;                int lastRet = -1;                int expectedModCount = ArrayList.this.modCount;

public boolean hasNext() {return cursor != SubList.this.size;}

@SuppressWarnings("unchecked")public E next() {                    checkForComodification();                    int i = cursor;                    if (i >= SubList.this.size)throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;                    if (offset + i >= elementData.length)throw new ConcurrentModificationException();cursor = i + 1;                    return (E) elementData[offset + (lastRet = i)];}

public boolean hasPrevious() {return cursor != 0;}

@SuppressWarnings("unchecked")public E previous() {                    checkForComodification();                    int i = cursor - 1;                    if (i < 0)throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;                    if (offset + i >= elementData.length)throw new ConcurrentModificationException();cursor = i;                    return (E) elementData[offset + (lastRet = i)];}

@SuppressWarnings("unchecked")public void forEachRemaining(Consumer<? super E> consumer) {                    Objects.requireNonNull(consumer);                    final int size = SubList.this.size;                    int i = cursor;                    if (i >= size) {return;}final Object[] elementData = ArrayList.this.elementData;                    if (offset + i >= elementData.length) {throw new ConcurrentModificationException();}while (i != size && modCount == expectedModCount) {                        consumer.accept((E) elementData[offset + (i++)]);}// update once at end of iteration to reduce heap write trafficlastRet = cursor = i;checkForComodification();}

public int nextIndex() {return cursor;}

public int previousIndex() {return cursor - 1;}

public void remove() {if (lastRet < 0)throw new IllegalStateException();checkForComodification();

try {                        SubList.this.remove(lastRet);cursor = lastRet;lastRet = -1;expectedModCount = ArrayList.this.modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}                }

public void set(E e) {if (lastRet < 0)throw new IllegalStateException();checkForComodification();

try {                        ArrayList.this.set(offset + lastRet, e);} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}                }

public void add(E e) {                    checkForComodification();

try {int i = cursor;SubList.this.add(i, e);cursor = i + 1;lastRet = -1;expectedModCount = ArrayList.this.modCount;} catch (IndexOutOfBoundsException ex) {throw new ConcurrentModificationException();}                }

final void checkForComodification() {if (expectedModCount != ArrayList.this.modCount)throw new ConcurrentModificationException();}            };}

public List<E> subList(int fromIndex, int toIndex) {subListRangeCheck(fromIndex, toIndex, size);            return new SubList(this, offset, fromIndex, toIndex);}

private void rangeCheck(int index) {if (index < 0 || index >= this.size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}

private void rangeCheckForAdd(int index) {if (index < 0 || index > this.size)throw new IndexOutOfBoundsException(outOfBoundsMsg(index));}

private String outOfBoundsMsg(int index) {return "Index: "+index+", Size: "+this.size;}

private void checkForComodification() {if (ArrayList.this.modCount != this.modCount)throw new ConcurrentModificationException();}

public Spliterator<E> spliterator() {            checkForComodification();            return new ArrayListSpliterator<E>(ArrayList.this, offset,offset + this.size, this.modCount);}    }

@Overridepublic void forEach(Consumer<? super E> action) {        Objects.requireNonNull(action);        final int expectedModCount = modCount;@SuppressWarnings("unchecked")final E[] elementData = (E[]) this.elementData;        final int size = this.size;        for (int i=0; modCount == expectedModCount && i < size; i++) {            action.accept(elementData[i]);}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}    }@Overridepublic Spliterator<E> spliterator() {return new ArrayListSpliterator<>(this, 0, -1, 0);}

/** Index-based split-by-two, lazily initialized Spliterator */static final class ArrayListSpliterator<E> implements Spliterator<E> {

private final ArrayList<E> list;        private int index; // current index, modified on advance/splitprivate int fence; // -1 until used; then one past last indexprivate int expectedModCount; // initialized when fence set

/** Create new spliterator covering the given  range */ArrayListSpliterator(ArrayList<E> list, int origin, int fence,                             int expectedModCount) {this.list = list; // OK if null unless traversedthis.index = origin;            this.fence = fence;            this.expectedModCount = expectedModCount;}

private int getFence() { // initialize fence to size on first useint hi; // (a specialized variant appears in method forEach)ArrayList<E> lst;            if ((hi = fence) < 0) {if ((lst = list) == null)                    hi = fence = 0;                else {expectedModCount = lst.modCount;hi = fence = lst.size;}            }return hi;}

public ArrayListSpliterator<E> trySplit() {int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;            return (lo >= mid) ? null : // divide range in half unless too smallnew ArrayListSpliterator<E>(list, lo, index = mid,expectedModCount);}

public boolean tryAdvance(Consumer<? super E> action) {if (action == null)throw new NullPointerException();            int hi = getFence(), i = index;            if (i < hi) {index = i + 1;@SuppressWarnings("unchecked") E e = (E)list.elementData[i];action.accept(e);                if (list.modCount != expectedModCount)throw new ConcurrentModificationException();                return true;}return false;}

public void forEachRemaining(Consumer<? super E> action) {int i, hi, mc; // hoist accesses and checks from loopArrayList<E> lst; Object[] a;            if (action == null)throw new NullPointerException();            if ((lst = list) != null && (a = lst.elementData) != null) {if ((hi = fence) < 0) {                    mc = lst.modCount;hi = lst.size;}elsemc = expectedModCount;                if ((i = index) >= 0 && (index = hi) <= a.length) {for (; i < hi; ++i) {@SuppressWarnings("unchecked") E e = (E) a[i];action.accept(e);}if (lst.modCount == mc)return;}            }throw new ConcurrentModificationException();}

public long estimateSize() {return (long) (getFence() - index);}

public int characteristics() {return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;}    }

@Overridepublic boolean removeIf(Predicate<? super E> filter) {        Objects.requireNonNull(filter);// figure out which elements are to be removed        // any exception thrown from the filter predicate at this stage        // will leave the collection unmodifiedint removeCount = 0;        final BitSet removeSet = new BitSet(size);        final int expectedModCount = modCount;        final int size = this.size;        for (int i=0; modCount == expectedModCount && i < size; i++) {@SuppressWarnings("unchecked")final E element = (E) elementData[i];            if (filter.test(element)) {                removeSet.set(i);removeCount++;}        }if (modCount != expectedModCount) {throw new ConcurrentModificationException();}// shift surviving elements left over the spaces left by removed elementsfinal boolean anyToRemove = removeCount > 0;        if (anyToRemove) {final int newSize = size - removeCount;            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {                i = removeSet.nextClearBit(i);elementData[j] = elementData[i];}for (int k=newSize; k < size; k++) {elementData[k] = null;  // Let gc do its work}this.size = newSize;            if (modCount != expectedModCount) {throw new ConcurrentModificationException();}            modCount++;}

return anyToRemove;}

@Override    @SuppressWarnings("unchecked")public void replaceAll(UnaryOperator<E> operator) {        Objects.requireNonNull(operator);        final int expectedModCount = modCount;        final int size = this.size;        for (int i=0; modCount == expectedModCount && i < size; i++) {elementData[i] = operator.apply((E) elementData[i]);}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}        modCount++;}

@Override    @SuppressWarnings("unchecked")public void sort(Comparator<? super E> c) {final int expectedModCount = modCount;Arrays.sort((E[]) elementData, 0, size, c);        if (modCount != expectedModCount) {throw new ConcurrentModificationException();}        modCount++;}}

版权声明:知识在于分享,技术在于交流,转载时请留一个博主的链接就好

时间: 2024-10-31 18:51:00

Java-ArrayList源码分析及示例的相关文章

Java - ArrayList源码分析

java提高篇(二一)-----ArrayList 一.ArrayList概述 ArrayList是实现List接口的动态数组,所谓动态就是它的大小是可变的.实现了所有可选列表操作,并允许包括 null 在内的所有元素.除了实现 List 接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小. 每个ArrayList实例都有一个容量,该容量是指用来存储列表元素的数组的大小.默认初始容量为10.随着ArrayList中元素的增加,它的容量也会不断的自动增长.在每次添加新的元素时,Array

Java ArrayList源码分析(有助于理解数据结构)

arraylist源码分析 1.数组介绍 数组是数据结构中很基本的结构,很多编程语言都内置数组,类似于数据结构中的线性表 在java中当创建数组时会在内存中划分出一块连续的内存,然后当有数据进入的时候会将数据按顺序的存储在这块连续的内存中.当需要读取数组中的数据时,需要提供数组中的索引,然后数组根据索引将内 存中的数据取出来,返回给读取程序.在Java中并不是所有的数据都能存储到数组中,只有相同类型的数据才可以一起存储到数组中.    因为数组在存储数据时是按顺序存储的,存储数据的内存也是连续的

Java集合系列之ArrayList源码分析

一.ArrayList简介 ArrayList是可以动态增长和缩减的索引序列,它是基于数组实现的List类. 该类封装了一个动态再分配的Object[]数组,每一个类对象都有一个capacity属性,表示它们所封装的Object[]数组的长度,当向ArrayList中添加元素时,该属性值会自动增加.如果想ArrayList中添加大量元素,可使用ensureCapacity方法一次性增加capacity,可以减少增加重分配的次数提高性能. ArrayList的用法和Vector向类似,但是Vect

JAVA Collection 源码分析(一)之ArrayList

到今天为止,差不多已经工作一年了,一直在做的是javaweb开发,一直用的是ssh(sh)别人写好的框架,总感觉自己现在高不成低不就的,所以就像看看java的源码,顺便学习一下大牛的思想和架构,read and write一直是提高自己编程水平的不二法门,写博客只是记录自己的学习历程,方便回顾,写的不好的地方,请多多包含,不喜勿喷,好了废话少说,现在让我们开始我们的历程把,Let's go!!!!!!!! 想看源码无从下手,不知道有没有跟我一样感觉的人们,今天用Intellij发现了可以找出类与

java io系列03之 ByteArrayOutputStream的简介,源码分析和示例(包括OutputStream)

前面学习ByteArrayInputStream,了解了“输入流”.接下来,我们学习与ByteArrayInputStream相对应的输出流,即ByteArrayOutputStream.本章,我们会先对ByteArrayOutputStream进行介绍,在了解了它的源码之后,再通过示例来掌握如何使用它. 转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_03.html ByteArrayOutputStream 介绍 ByteArrayOutpu

java io系列02之 ByteArrayInputStream的简介,源码分析和示例(包括InputStream)

我们以ByteArrayInputStream,拉开对字节类型的“输入流”的学习序幕.本章,我们会先对ByteArrayInputStream进行介绍,然后深入了解一下它的源码,最后通过示例来掌握它的用法. 转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_02.html ByteArrayInputStream 介绍 ByteArrayInputStream 是字节数组输入流.它继承于InputStream.它包含一个内部缓冲区,该缓冲区包含从流

Java集合源码分析(二)ArrayList

ArrayList简介 ArrayList是基于数组实现的,是一个动态数组,其容量能自动增长,类似于C语言中的动态申请内存,动态增长内存. ArrayList不是线程安全的,只能用在单线程环境下,多线程环境下可以考虑用Collections.synchronizedList(List l)函数返回一个线程安全的ArrayList类,也可以使用concurrent并发包下的CopyOnWriteArrayList类. ArrayList实现了Serializable接口,因此它支持序列化,能够通过

java io系列04之 管道(PipedOutputStream和PipedInputStream)的简介,源码分析和示例

本章,我们对java 管道进行学习. 转载请注明出处:http://www.cnblogs.com/skywang12345/p/io_04.html java 管道介绍 在java中,PipedOutputStream和PipedInputStream分别是管道输出流和管道输入流.它们的作用是让多线程可以通过管道进行线程间的通讯.在使用管道通信时,必须将PipedOutputStream和PipedInputStream配套使用.使 用管道通信时,大致的流程是:我们在线程A中向PipedOut

Java笔记---ArrayList源码分析

一.前言 一直就想看看java的源码,学习一下大牛的编程.这次下狠心花了几个晚上的时间,终于仔细分析了下 ArrayList 的源码(PS:谁说的一个晚上可以看完的?太瞎扯了).现在记录一下所得. 二.ArrayList 源码分析 2.1 如何分析? 想要分析下源码是件好事,但是如何去进行分析呢?以我的例子来说,我进行源码分析的过程如下几步: 找到类:利用 Eclipse 找到所需要分析的类(此处就是 ArrayList) 新建类:新建一个类,命名为 ArrayList,将源码拷贝到该类.因为我

JAVA Collection 源码分析(二)之SubList

昨天我们分析了ArrayList的源码,我们可以看到,在其中还有一个类,名为SubList,其继承了AbstractList. // AbstractList类型的引用,所有继承了AbstractList都可以传进来 private final AbstractList<E> parent; // 这个是其实就是parent的偏移量,从parent中的第几个元素开始的 private final int parentOffset; private final int offset; int s