I came across newArrayListWithCapacity(int)
(1) in the codebase and was wondering if it has any advantages.
From what I understand, if we don't know the size, new ArrayList
is going to serve the purpose, and if we do now the exact size, we can simply use an array. I'm trying to understand the benefits of using newArrayListWithCapacity(int)
. And how is it different from newArrayListWithExpectedSize
?
If I define the expected size as x
and if I end up having y
number of entries, does it adversely affect the performance?
@GwtCompatible(serializable=true) public static ArrayList newArrayListWithCapacity(int initialArraySize) Creates an ArrayList instance backed by an array of the exact size specified; equivalent to ArrayList.ArrayList(int). Note: if you know the exact size your list will be, consider using a fixed-size list (Arrays.asList(Object[])) or an ImmutableList instead of a growable ArrayList.
Note: If you have only an estimate of the eventual size of the list, consider padding this estimate by a suitable amount, or simply use newArrayListWithExpectedSize(int) instead.