Characteristics of array

1. Efficient random access

2. Inefficient insertion and deletion

The optimization scheme of array insertion :
If the data in the array is in order, when we insert a new element at a certain position, we must move the data after k according to the method just now. However, if the data stored in the array does not have any rules, the array is just treated as a collection of stored data. In this case, if you want to insert an array into the k-th position, in order to avoid large-scale data movement, we have a simple way to directly move the k-th position data to the end of the array element. Put the new element directly into the kth position. This kind of processing idea will be used in the fast queue.

Optimized solution for array deletion:
we can first record the deleted data. Each delete operation does not actually move the data, but the recorded data has been deleted. When the array has no more space to store data, we trigger a real delete operation again, which greatly reduces the data movement caused by the delete operation. This kind of processing idea is like JVM mark removal garbage collection algorithm.

ArrayList source code analysis:
1: When creating an ArrayList, use the default constructor to create a collection and then add elements to it. The array is expanded to the size of 10 when it is added for the first time, and elements added afterwards will not expand until the 11th time. The expansion is rounded by 1.5 times, and then if the expansion is needed, it is rounded by 1.5 times, but the maximum value of the expansion is Integer.MAX_VALUE.
2: A new array is created each time the capacity is expanded, and then the data in the original array is moved to the new array.
So back to what we said at the beginning: If you can determine the size of the data to be stored in advance, it is best to create an ArrayList When specifying the data size in advance.
3: Java ArrayList cannot store basic types, such as int and long, and needs to be encapsulated as Integer and Long classes.

Time complexity: If you
use array storage, you can find the specified element in O(logn) time by using the dichotomy.
The time complexity required to insert and delete this action is O(n).

Guess you like

Origin blog.csdn.net/weixin_41699562/article/details/103931845