guava下Lists,newArrayListWithExpectedSize()和newArrayListWithCapacity()使用示例


guava  Lists下通過了兩個創建指定容量的list方法,newArrayListWithExpectedSize,newArrayListWithCapacity。它們主要的區別如下:

源碼:

public static <E> ArrayList<E> newArrayListWithCapacity(int initialArraySize) {
        CollectPreconditions.checkNonnegative(initialArraySize, "initialArraySize"); return new ArrayList(initialArraySize); }
 public static <E> ArrayList<E> newArrayListWithExpectedSize(int estimatedSize) {
        return new ArrayList(computeArrayListCapacity(estimatedSize)); } @VisibleForTesting static int computeArrayListCapacity(int arraySize) { CollectPreconditions.checkNonnegative(arraySize, "arraySize"); return Ints.saturatedCast(5L + (long)arraySize + (long)(arraySize / 10)); }

通過方法**Size參數創建一個定容的集合。

1、如果你確定你的容器裝多少個,不會改變,一般直接使用

newArrayListWithCapacity(),如果容器超過定義size,它會自動擴容,不用擔心容量不夠。擴容后,會將原來的數組復制到新的數組中,但擴容會帶來一定的性能影響:包括開辟新空間,copy數據,耗時,耗性能

2、如果你的不確定你的容器多少個,但增幅不會太大,使用

newArrayListWithExpectedSize(),會直接創建一個指定size的容器,但它會通過一條公式計算來進行擴容 (

5L + (long)arraySize + (long)(arraySize / 10)

),例如,創建一個10個size的容器,那么 5+10 + (10/10) = 16,當容器添加第17個數據時,這個容器才會進行擴容,優點:節約內存,節約時間,節約性能,

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM