可变数组集合ArrayList
生活随笔
收集整理的這篇文章主要介紹了
可变数组集合ArrayList
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
List 接口的大小可變數組的實現。實現了所有可選列表操作,并允許包括 null 在內的所有元素。除了實現 List 接口外,此類還提供一些方法來操作內部用來存儲列表的數組的大小。(此類大致上等同于 Vector 類,除了此類是不同步的。)
每個ArrayList實例都有一個容量,默認長度是10,ArrayList將添加的對象實質上
是保存在Object數組中,當保存對象的數量足夠多且達到容器長度的最大值時,ArrayList
會進行擴容,每次擴容大小的當前數組長度的1/2,保存的元素可以是Null值 且可以重復。
主要特征:
1.未了保證容器有足夠多的空間保存元素,又不浪費內存空間,每次添加元素都要確認長度是否
夠用,如果達到容量上限,將進行擴容。
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);} View Code2.為了實現快速查詢,類內部通過屬性size來對元素進行計數
/*** The size of the ArrayList (the number of elements it contains).** @serial*/private int size; View Code public boolean add(E e) {ensureCapacityInternal(size + 1); // Increments modCount!!elementData[size++] = e;return true;} View Code3.在刪除元素時,所有在刪除元素索引位置的其他元素將往左移,對性能有一定影響
/*** Removes the element at the specified position in this list.* Shifts any subsequent elements to the left (subtracts one from their* indices).** @param index the index of the element to be removed* @return the element that was removed from the list* @throws IndexOutOfBoundsException {@inheritDoc}*/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 workreturn oldValue;} View Code4.元素替換操作是指定索引位置,修改當前索引位置變量指向的內存地址,并未引起位置變動,所以性能是沒問題的。
?
public E set(int index, E element) {rangeCheck(index);E oldValue = elementData(index);elementData[index] = element;return oldValue;} View Code?
轉載于:https://www.cnblogs.com/liandy0906/p/7231175.html
總結
以上是生活随笔為你收集整理的可变数组集合ArrayList的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 7.24笔记
- 下一篇: 日记-2017-7-24-cp-css-