1. 程式人生 > >JDK 源碼解讀之 ArrayList

JDK 源碼解讀之 ArrayList

ont xtend empty 文檔 code access extend ces doesn

技術分享
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
View Code

  文檔中提到:size isEmpty get set iterator listIterator 操作,是( run in constant time), add操作是(run in amortized constant time),而 其他的操作是 (run in linear time).

  Constant time means the operation doesn‘t depend on the length of the input. Linear time means the operation grows linearly with the change in the length of the input.

  就想比較 兩個(4bytes int a ,b)的大小是 constant time,並不會因為 a,b的大小而不同。用大O表示法就是:O(1)。而 找出一個數組中 最大的 值,就是Linear time,因為時間隨著 數組中元素的增加而增加。用大O表示法就是:O(n)。

  什麽是amortized constant time呢?

  StackOverFlow上是這麽說的:

    If you do an operation say a million times, you don‘t really care about the worst-case or the best-case of that operation - what you care about is how much time is taken in total when you repeat the operation a million times.

   Essentially amortised time means "average time taken per operation, if you do many operations". Amortised time doesn‘t have to be constant; you can have linear and logarithmic amortised time or whatever else.

  

JDK 源碼解讀之 ArrayList