摘要:每次迭代器進(jìn)結(jié)構(gòu)性修改的時(shí)候都將和進(jìn)行對(duì)比如果兩種相等則說明沒有其他迭代器修改了對(duì)象,可以進(jìn)行。
一、ArrayList簡介
ArrayList的內(nèi)部實(shí)現(xiàn)了動(dòng)態(tài)數(shù)組,提供了動(dòng)態(tài)的增加和減少元素,繼承AbstractList類,并且實(shí)現(xiàn)了List、RandomAccess、Cloneable和java.io.Serializable接口。ArrayList是一個(gè)數(shù)組隊(duì)列,提供添加、刪除、修改和遍歷元素的功能。因?yàn)閷?shí)現(xiàn)RandomAccess接口,提供了隨機(jī)訪問的功能。現(xiàn)了Cloneable接口,即覆蓋了函數(shù)clone(),能被克隆。現(xiàn)java.io.Serializable接口,這意味著ArrayList支持序列化。ArrayList不是線程安全的,建議在單線程中訪問。
ArrayList有三個(gè)構(gòu)造方法,定義如下:
//創(chuàng)建給定初始化大小的ArrayList public ArrayList(int initialCapacity) {} //默認(rèn)無參構(gòu)造方法創(chuàng)建的ArrayList public ArrayList() {} //創(chuàng)建給定初始化集合c的ArrayList public ArrayList(Collection extends E> c) {}二、源碼分析
ArrayList是通過動(dòng)態(tài)數(shù)組實(shí)現(xiàn)的,下面通過源碼分析ArrayList的實(shí)現(xiàn):
1、ArrayList主要源碼分析public class ArrayList2、Itr和ListItr源碼分析extends AbstractList implements List , RandomAccess, Cloneable, java.io.Serializable { /** * 默認(rèn)初始化大小 */ private static final int DEFAULT_CAPACITY = 10; /** * 空數(shù)組實(shí)例 */ private static final Object[] EMPTY_ELEMENTDATA = {}; /** * 判斷是否為第一次添加元素 */ private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; /** * ArrayList保存元素?cái)?shù)據(jù),通過elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 來判斷是否是第一次添加元素 */ transient Object[] elementData; /** * ArrayList的實(shí)際大小 */ private int size; /** * 創(chuàng)建大小為initialCapacity的空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); } } /** * 創(chuàng)建初始化容量為10的list */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** * 通過集合c創(chuàng)建list * @param c the collection whose elements are to be placed into this list * @throws NullPointerException 如果c為nulll,有空指針異常 */ 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; } } /** * 縮小list容量為當(dāng)前真實(shí)大小 */ public void trimToSize() { modCount++; if (size < elementData.length) { elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size); } } //外部調(diào)用方法,調(diào)整容量,確保list不會(huì)越界 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); } } //計(jì)算容量 private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } return minCapacity; } //內(nèi)部調(diào)用方法,調(diào)整容量,確保list不會(huì)越界 private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } //擴(kuò)展容量 private void ensureExplicitCapacity(int minCapacity) { modCount++; // 如果最小容量大于數(shù)組大小,進(jìn)行數(shù)組擴(kuò)展 if (minCapacity - elementData.length > 0) grow(minCapacity); } /** * 數(shù)組容量的最大值。部分虛擬機(jī)限制,大于MAX_ARRAY_SIZE,會(huì)導(dǎo)致OutOfMemoryError */ private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /** * 數(shù)組按照1.5倍增加,如果增加后的值小于minCapacity,按照minCapacity增加 * */ private void grow(int minCapacity) { int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; // 是否大于最大值 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); } //如果擴(kuò)展容量大于最大值,按照最大值擴(kuò)展 private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } /** * 返回list實(shí)際大小 */ public int size() { return size; } /** * 如果實(shí)際大小為0,返回true. */ public boolean isEmpty() { return size == 0; } /** * 返回元素是否存在,indexOf(o)方法返回-1表示不存在. */ public boolean contains(Object o) { return indexOf(o) >= 0; } /** * 返回元素的下標(biāo),-1表示元素不存在 */ 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; } /** * 返回最后一個(gè)元素o的下標(biāo) */ 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; } /** * copy一個(gè)list對(duì)象 */ 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); } } /** * 將list轉(zhuǎn)換為對(duì)象 */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** * 將list轉(zhuǎn)換為對(duì)應(yīng)類型的數(shù)組,如果數(shù)組大小小于size,通過Arrays.copyOf轉(zhuǎn)換,如果大于System.arraycopy轉(zhuǎn)換 */ public 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; } //通過制定下標(biāo)返回一個(gè)元素 E elementData(int index) { return (E) elementData[index]; } /** * 根據(jù)下標(biāo)獲取元素 * */ 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; } /** * 在list中添加一個(gè)元素 */ public boolean add(E e) { //調(diào)整大小 ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } /** * 在指定位置添加一個(gè)元素 */ public void add(int index, E element) { rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!! //index之后的元素后移 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); //將最后一個(gè)對(duì)象置空,便于GC elementData[--size] = null; return oldValue; } /** * 根據(jù)指定的元素移除,調(diào)用fastRemove(index)方法 */ 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 } /** * 清除所有元素,size賦值0, */ public void clear() { modCount++; // clear to let GC do its work for (int i = 0; i < size; i++) elementData[i] = null; size = 0; } /** * 將集合c中的元素添加到list中 */ 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; } /** * 將集合c中的元素添加到index開始的位置,原index之后的元素后移 */ 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; } /** * 刪除指定區(qū)間的元素 */ 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 work int 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)); } /** * 添加時(shí)檢查是否越界 */ private void rangeCheckForAdd(int index) { if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * 越界后返回的異常詳細(xì)信息 */ private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } /** * 刪除集合c中所有元素,首選檢查c是否為空,調(diào)用batchRemove(c, false)方法 */ public boolean removeAll(Collection> c) { Objects.requireNonNull(c); return batchRemove(c, false); } /** * 保留給定集合的元素,刪除其他的 * */ public boolean retainAll(Collection> c) { Objects.requireNonNull(c); return batchRemove(c, true); } /** * 根據(jù)complement判斷是刪除還是保留給定的集合元素 * */ 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++) //將刪除或者保留的元素移動(dòng)到數(shù)據(jù)前面 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; } //把w下標(biāo)后的數(shù)據(jù)刪除 if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified; } /** * 將ArrayList保存到流中 */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException{ // Write out element count, and any hidden stuff int 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 0) { // be like clone(), allocate array based upon size not capacity int capacity = calculateCapacity(elementData, size); SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity); ensureCapacityInternal(size); Object[] a = elementData; // Read in all elements in the proper order. for (int i=0; i listIterator(int index) { if (index < 0 || index > size) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } /** * 返回從0開始的ListIterator迭代器 */ public ListIterator listIterator() { return new ListItr(0); } /** * 返回Iterator迭代器 */ public Iterator iterator() { return new Itr(); } /** * 定義一個(gè)基于AbstractList.Itr優(yōu)化后的迭代器內(nèi)部類,后面詳細(xì)分析 */ private class Itr implements Iterator {} /** * 定義一個(gè)基于 AbstractList.ListItr優(yōu)化后的迭代器內(nèi)部類,后面詳細(xì)分析 */ private class ListItr extends Itr implements ListIterator {} /** *返回一個(gè)從fromIndex到toIndex的子list */ public List subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); } //檢查獲取子list的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 + ")"); } //子list內(nèi)部類 private class SubList extends AbstractList implements RandomAccess {} @Override public 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(); } } /** * Creates a late-binding * and fail-fast {@link Spliterator} over the elements in this * list. * * The {@code Spliterator} reports {@link Spliterator#SIZED}, * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}. * Overriding implementations should document the reporting of additional * characteristic values. * * @return a {@code Spliterator} over the elements in this list * @since 1.8 */ @Override public Spliterator
spliterator() { return new ArrayListSpliterator<>(this, 0, -1, 0); } /** Index-based split-by-two, lazily initialized Spliterator */ static final class ArrayListSpliterator implements Spliterator { } @Override public 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 unmodified int 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 elements final 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 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++; } }
上面分析了ArrayList源碼,其中Itr和ListItr這兩個(gè)內(nèi)部類沒有詳細(xì)介紹。Itr和ListItr在AbstractList中有實(shí)現(xiàn),在ArrayList對(duì)其進(jìn)行了優(yōu)化。下面進(jìn)行詳細(xì)介紹:
Itr
Itr實(shí)現(xiàn)了Iterator接口,源碼如下:
private class Itr implements Iterator{ //下一個(gè)元素的下標(biāo) int cursor; // index of next element to return //最后返回元素的下標(biāo),如果不存在,返回-1 int lastRet = -1; /** * 每個(gè)迭代器保存一個(gè)expectedModCount ,來記錄這個(gè)迭代器對(duì)對(duì)象進(jìn)行結(jié)構(gòu)性修改的次數(shù)。 * 每次迭代器進(jìn)結(jié)構(gòu)性修改的時(shí)候都將expectedModCount 和modCount進(jìn)行對(duì)比 * 如果兩種相等則說明沒有其他迭代器修改了對(duì)象,可以進(jìn)行。如果不相等則說明有迭代進(jìn)行了修改,立刻拋出異常 */ int expectedModCount = modCount; Itr() {} //下一個(gè)元素下標(biāo)不等于size,表示還有下一個(gè)元素 public boolean hasNext() { return cursor != size; } //獲取到下一個(gè)元素 public E next() { //檢查其他迭代器對(duì)list是否有修改 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(); } //移動(dòng)元素 while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
ListItr
ListItr繼承自Itr,并且實(shí)現(xiàn)了ListIterator接口,源碼如下:
private class ListItr extends Itr implements ListIterator三、使用示例 1、ArrayList的四種遍歷方式{ 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(); } } }
jdk 1.8以前的集合list遍歷支持三種方式,在1.8中增加了java 8 forEach方法,下面分別分析這四種遍歷方式以及效率:
public class ArrayListIteratorTest { public static void main(String[] args) { List list = new ArrayList(); for (int i = 0; i < 1000000 ; i++) { list.add(i); } iteratorTest(list); foreashITest(list); foreashTest(list); java8ForeashTest(list); } /** * 通過迭代器遍歷 * @param list */ static void iteratorTest(List list){ long startTime; long endTime; startTime = System.currentTimeMillis(); Iterator iterator = list.iterator(); while (iterator.hasNext()){ iterator.next(); } endTime = System.currentTimeMillis(); System.out.println("Iterator time :" + (endTime - startTime)); } /** * 通過索引遍歷 * @param list */ static void foreashITest(List list){ long startTime; long endTime; startTime = System.currentTimeMillis(); for (int i = 0, length = list.size(); i < length; i++) { list.get(i); } endTime = System.currentTimeMillis(); System.out.println("fori time :" + (endTime - startTime)); } /** * 通過foreash遍歷 * @param list */ static void foreashTest(List list){ long startTime; long endTime; startTime = System.currentTimeMillis(); for (Object l: list) { } endTime = System.currentTimeMillis(); System.out.println("foreash time :" + (endTime - startTime)); } /** * 通過java 8 中提供的foreash遍歷 * @param list */ static void java8ForeashTest(List list){ long startTime; long endTime; startTime = System.currentTimeMillis(); list.forEach(l->{}); endTime = System.currentTimeMillis(); System.out.println("java 8 foreash time :" + (endTime - startTime)); } }
以上代碼運(yùn)行后的結(jié)果如下:
從運(yùn)行結(jié)果看,foreash運(yùn)行效率最高,java 8 中的foreash運(yùn)行效率最差。
2、toArray()方法的使用ArrayList中提供了連個(gè)方法將list轉(zhuǎn)換為數(shù)組,分別是Object[] toArray()和
public class ArrayListToArraysTest { public static void main(String[] args) { List3、fail-fast機(jī)制list = new ArrayList<>(); Dog dog1 = new Dog(); Dog dog2 = new Dog(); list.add(dog1); list.add(dog2); //此處會(huì)拋出異常 Dog[] dogs1 = (Dog[]) list.toArray(); System.out.println(Arrays.toString(dogs1)); Dog[] dogs2 = new Dog[list.size()]; dogs2 = list.toArray(dogs2); System.out.println(Arrays.toString(dogs2)); } private static class Dog{ private String name; private String color; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } } }
當(dāng)某一個(gè)線程A通過iterator去遍歷某集合的過程中,若該集合的內(nèi)容被其他線程所改變了;那么線程A訪問集合時(shí),就會(huì)拋出ConcurrentModificationException異常,產(chǎn)生fail-fast事件。
Fail-fast示例如下:
public class ArrayListFailFastTest { private static List list = new ArrayList(); public static void main(String[] args) { Thread t1 = new Thread(new ThreadTest(),"t1"); Thread t2 = new Thread(new ThreadTest(), "t2"); t1.start(); t2.start(); } private static class ThreadTest implements Runnable{ @Override public void run() { for (int i = 0; i < 20; i++) { list.add(i); } Iterator iterator = list.iterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " "); } } } }
可以看出,在多線程下,通過iterator去遍歷某集合,會(huì)拋ConcurrentModificationException異常。
四、總結(jié)在本章中,分析了ArrayList集合。ArrayList的內(nèi)部是通過動(dòng)態(tài)數(shù)組存儲(chǔ)數(shù)據(jù)的,默認(rèn)初始大小是10,在jdk1.8中,默認(rèn)構(gòu)造方法創(chuàng)建對(duì)象,默認(rèn)的數(shù)組為空,當(dāng)?shù)谝淮翁砑釉貢r(shí),設(shè)置數(shù)組大小為10。在調(diào)整數(shù)組大小時(shí),默認(rèn)是增加原數(shù)組的1.5倍,如果傳入的最小擴(kuò)展數(shù)大于增加1.5倍后的大小,則按照此最小擴(kuò)展數(shù)擴(kuò)展,否則按照默認(rèn)擴(kuò)展。
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/71983.html
摘要:我的是忙碌的一年,從年初備戰(zhàn)實(shí)習(xí)春招,年三十都在死磕源碼,三月份經(jīng)歷了阿里五次面試,四月順利收到實(shí)習(xí)。因?yàn)槲倚睦砗芮宄业哪繕?biāo)是阿里。所以在收到阿里之后的那晚,我重新規(guī)劃了接下來的學(xué)習(xí)計(jì)劃,將我的短期目標(biāo)更新成拿下阿里轉(zhuǎn)正。 我的2017是忙碌的一年,從年初備戰(zhàn)實(shí)習(xí)春招,年三十都在死磕JDK源碼,三月份經(jīng)歷了阿里五次面試,四月順利收到實(shí)習(xí)offer。然后五月懷著忐忑的心情開始了螞蟻金...
摘要:一簡介內(nèi)部是通過雙向鏈表存儲(chǔ)的,提供順序訪問。繼承了,實(shí)現(xiàn)在迭代器上的隨機(jī)訪問。四總結(jié)本節(jié)分析了的源碼的用法。實(shí)現(xiàn)了接口,內(nèi)部通過鏈表實(shí)現(xiàn),能夠?qū)崿F(xiàn)鏈表隊(duì)列棧和雙端隊(duì)列等數(shù)據(jù)結(jié)構(gòu)的功能。 一、LinkedList簡介 LinkedList內(nèi)部是通過雙向鏈表存儲(chǔ)的,提供順序訪問。繼承了AbstractSequentialList,實(shí)現(xiàn)在迭代器上的隨機(jī)訪問。并且,還實(shí)現(xiàn)了List、Dequ...
摘要:是棧,它繼承于。滿二叉樹除了葉結(jié)點(diǎn)外每一個(gè)結(jié)點(diǎn)都有左右子葉且葉子結(jié)點(diǎn)都處在最底層的二叉樹。沒有鍵值相等的節(jié)點(diǎn)。這是數(shù)據(jù)庫選用樹的最主要原因。 在我們學(xué)習(xí)Java的時(shí)候,很多人會(huì)面臨我不知道繼續(xù)學(xué)什么或者面試會(huì)問什么的尷尬情況(我本人之前就很迷茫)。所以,我決定通過這個(gè)開源平臺(tái)來幫助一些有需要的人,通過下面的內(nèi)容,你會(huì)掌握系統(tǒng)的Java學(xué)習(xí)以及面試的相關(guān)知識(shí)。本來是想通過Gitbook的...
摘要:而在集合中,值僅僅是一個(gè)對(duì)象罷了該對(duì)象對(duì)本身而言是無用的。將這篇文章作為集合的總結(jié)篇,但覺得沒什么好寫就回答一些面試題去了,找了一會(huì)面試題又覺得不夠系統(tǒng)。 前言 聲明,本文用的是jdk1.8 花了一個(gè)星期,把Java容器核心的知識(shí)過了一遍,感覺集合已經(jīng)無所畏懼了!!(哈哈哈....),現(xiàn)在來總結(jié)一下吧~~ 回顧目錄: Collection總覽 List集合就這么簡單【源碼剖析】 Ma...
閱讀 4723·2021-11-15 11:39
閱讀 2691·2021-11-11 16:55
閱讀 2200·2021-10-25 09:44
閱讀 3504·2021-09-22 16:02
閱讀 2433·2019-08-30 15:55
閱讀 3122·2019-08-30 13:46
閱讀 2656·2019-08-30 13:15
閱讀 1944·2019-08-30 11:12