When an ArrayList resizes, how many elements does it add?

Java ArrayList dynamically expands when needed. How many elements does it add when expansion occurs?

And will he copy the old array to the new one, or does he somehow bind them together?

+3
source share
3 answers

Check out the source code :

int newCapacity = (oldCapacity * 3)/2 + 1;

The exact coefficient is different in implementation, gnu uses a coefficient of 2. This is not a big deal, it's just trading memory for speed.

It copies all the elements to a new array.

+9
source

double, , . ( , Java.)

: ? , , ?

: n , n + 1 n 2n. , n ( "" ) ( ), n/n 1 .

(. .)

+4

, /JavaDoc:

The details of the growth policy are not indicated beyond the fact that adding an item has a constant amortized cost of time.

This means that the internal array cannot be modified by adding a constant number, but some multiplication must be used. As maartinus indicated that Sun JDK and OpenJDK multiply size by 1.5 (approximately).

0
source

Source: https://habr.com/ru/post/1789171/


All Articles