Reputation: 1920
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.
Upvotes: 0
Views: 476
Reputation: 35467
The method and the constructor do the same thing, which is to provide an ArrayList
with a specific capacity, meaning that the initial backing array is created with the provided size.
Guava created a factory method wrapping the ArrayList(int)
constructor because, while well documented, it might sometimes lead people in confusion. The Guava team did the same with other collection factory methods such as Sets.newHashSetWithCapacity(int)
and Sets.newHashSetWithExpectedSize(int)
.
The pros are the following:
<FullTypeName>
to each constructor calls (such as List<String> strings = new ArrayList<String>(10)
). Nowadays you can simply use <>
(such as List<String> strings = new ArrayList<>(10)
, but at the time the gain was huge!The cons are:
The Guava team made that method because the pros clearly outmatch the cons in their view (which i personally share).
Upvotes: 1