I want to be clear on something: When using an arraylist, it starts with a size of 10 elements. If it needs to auto-increase, it rewrites the whole arrayList to be 2/3 larger.
If I'm looking at a list that will eventually be size 50-120, is it better to:
Thanks
ArrayList is a highly optimized and very efficient wrapper on top of a plain Java array. A small timing overhead comes from copying array elements, which happens when the allocated size is less than required number of elements.
An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one.
Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold.
On the other hand, java ArrayList does not have length property. The java ArrayList has size() method for ArrayList which provides the total number of objects available in the collection. We use length property to find length of Array in Java and size() to find size of ArrayList.
If you know the likely eventual size of the ArrayList
, it's usually best to specify it upfront:
ArrayList myList = new ArrayList(150);
This saves you the performance impact of having ArrayList
re-allocate the array used to store its content (although, for the array size that you've specified, this impact will be negligible).
It is less computationally intensive to make it about as large as you will need right off the bat, but the truth is that java is very efficient, so it really isn't necessary to worry about how the arraylist is increased. However, if you are going for maximum efficiency, then yes, allocating the memory when you create the list is better.
it rewrites the whole arrayList to be 2/3 larger
No. It makes the array twice as large (although the exact factor is an undocumented implementation detail). I stand corrected.
If I'm looking at a list that will eventually be size 50-120, is it better to: 1. create it size 150 right off
Why 150? Why not 120?
- allow the list to be auto-increased a few times?
In such a small range I would use the large size right away. If the span was much larger (e.g. 50–50000) I would reserve the smallest size (or perhaps an intermediate size, depending on the expected value distribution) and let it resize a few times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With