After all, the implementation class of List that is often used is ArrayList. Here are three points to keep in mind as you should use it efficiently if you use it with all your might.
ArrayList is a class for realizing variable length arrays. It is implemented internally using arrays, but regular arrays are fixed length. So, how to realize variable length is to create a new array of larger size and copy the data to it when the array prepared at the beginning is insufficient. Also, when inserting data in the middle, all subsequent elements are copied and shifted. As the size of the array increases, the process of regenerating and copying such an array becomes very slow, so it is important to prevent such processing from occurring in order to use ArrayList efficiently.
You can specify the initial size in the ArrayList constructor. Since the array is generated first with the specified initial size, the array will not be regenerated until it exceeds that size.
For example, if the number of elements is 100 at most, ArrayList is generated with an initial capacity of 100 by doing the following.
List<String> list = new ArrayList<String>(100);
ensureCapacity ensureCapacity is a method to ensure the size of ArrayList. It is used when the initial size specified in the constructor is likely to be greatly exceeded. For example, when adding 1000 elements to an ArrayList initialized with an initial size of 100, if you add 1000 times normally, regeneration may occur several times in the middle, but with ensureCapacity, the size is expanded to 1000 in advance. If you do, you only have to do it once.
trimToSize trimToSize is a method that trims the size of ArrayList by the current number of elements. For example, if the ArrayList initialized with the initial size 1000 contains only 100 elements, the area for 900 elements will be wasted, so the area will be released by truncating it. Of course, the size will be smaller, so if you try to add an element after that, you will have to reallocate the array. Therefore, it is recommended to use it when the element is not added in the subsequent processing.
Recommended Posts