Many List implementations have an option to specify an initial capacity for the collection, why is this not allowed for CopyOnWriteArrayList?
Asked
Active
Viewed 1,042 times
2
-
Why do you think you would need one? – Sotirios Delimanolis Sep 13 '16 at 22:29
-
I know the operations are expensive because it gives a fresh copy every time, but hadn't closely looked at the constructor before. This [answer](http://stackoverflow.com/a/39453595/2063026) got me thinking that this is not even possible. `CopyOnWriteArrayList` is an extremely poor choice to be used in a parallel stream operating on a large collection – vsnyc Sep 13 '16 at 22:33
1 Answers
10
In a conventional ArrayList
the capacity is a hint to reserve more space in the backing array for more elements to be added to the list later on.
In a CopyOnWriteArrayList
, every (atomic) write operation creates a new backing array. There is no point in preallocating an array that is bigger than the current list size because that space would never be used.

Stephen C
- 698,415
- 94
- 811
- 1,216
-
Thanks, that generally makes sense. I was hoping to achieve some performance gains by allocating a bigger capacity when working with large collections. Clearly, this would be a wrong choice of data structure to use (for frequent writes) – vsnyc Sep 13 '16 at 22:45
-
*Clearly, this would be a wrong choice of data structure to use (for frequent writes)* -- Absolutely correct! – Stephen C Sep 14 '16 at 01:49