The default capacity of ArrayList is 10, so if you need to handle large amounts of data with ArrayList, you need to use the method of explicitly specifying the capacity. This can reduce unnecessary expansion operations.
The main reason is that the expansion operation of ArrayList requires extra space, and it uses the Arrays.copyOf method for copying:
The Arrays.copyOf method uses the method of allocating space and then copying, which is very likely to cause OOM.
The default capacity of HashMap is 16, and its capacity must be a power of 2.
If the specified capacity is not a power of 2, it will also find the power of 2 closest to the current capacity.
The reason why it is a power of 2 is because the masters of SUN found that when the capacity is 2^n,
(length - 1) & hash is faster than modulo operation.
Use % time: 16 Use & time: 9
We take length as 16 as an example
When our hash is 17
The reason is because the binary of 16 - 1 is 01111 and the binary of 17 is 1 0001
We only need to calculate the low bit, discard all the high bits, and perform & operation on the low bit, the result is 1 and the result of 17 % 16 is exactly the same.
LastMod 2023-10-08 (05461cf)