Lists.newArrayListWithExpectedSize( int estimatedSize) 構造一個期望長度為estimatedSize的ArrayList實例。
源碼:
public static <E> ArrayList<E> newArrayListWithExpectedSize(int estimatedSize) { return new ArrayList(computeArrayListCapacity(estimatedSize)); }
//計算集合的容量 @VisibleForTesting static int computeArrayListCapacity(int arraySize) { //判斷是否小於0,小於0則拋出異常。 CollectPreconditions.checkNonnegative(arraySize, "arraySize"); return Ints.saturatedCast(5L + (long)arraySize + (long)(arraySize / 10)); }
//檢查是否小於0 @CanIgnoreReturnValue static int checkNonnegative(int value, String name) { if (value < 0) { throw new IllegalArgumentException(name + " cannot be negative but was: " + value); } else { return value; } }
//判斷計算出來的數組長度是否在int的范圍內 public static int saturatedCast(long value) { if (value > 2147483647L) { return 2147483647; } else { return value < -2147483648L ? -2147483648 : (int)value; } }