I have multiple ArrayLists with the same capacity. I fill these lists by reading a file.
I know that one difference between an Array and an ArrayList is that the Array have a fixed capacity while the ArrayList have a variable capacity. You should explicitly specify the array length when you declare it, but the ArrayList re-size itself when gets full.
Any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array. Becouse of this I am thinking to:
A – explicitly initialize the rest of ArrayList’s with the capacity of first, so these lists will not have to resize themselves and copy the old array elements to the new one or,
B – I can renounce at rest of lists, I only declare the first list and the rest will be Arrays with the length of the ArrayList.
static ArrayList<ObjectType> list1 = new ArrayList<>(); ArrayList<ObjectType> list2 = new ArrayList<>(list1.size()); ArrayList<ObjectType> list2 = new ArrayList<>(list1.size()); ...
static ArrayList<ObjectType> list1 = new ArrayList<>(); ObjectType array1 = new ObjectType[list1.size()]; ObjectType array2 = new ObjectType[list1.size()]; ObjectType array3 = new ObjectType[array1.length]; ...
The questions are:
Is the A example a bad programming technique? But the B example?
Which example is better to be used?
Creating an ArrayList with an initial capacity is not a bad technique at all. In fact it’s going to give you a much better performance since it doesn’t have to reallocate memory and copy the existing contents everytime the size is full while you keep adding elements to the list.
From the Java docs,
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.