System.arraycopy: The Reallocation Mechanism
What you'll learn: How Java internally copies elements from an old array to a new, larger one when an ArrayList needs more capacity.
The Problem: Moving to a Bigger Array
When an ArrayList grows beyond its current capacity, Java can't simply "expand" the existing array in memory—arrays have fixed sizes. Instead, it must create a brand-new, larger array and copy all the existing elements over. This is where System.arraycopy comes in.
What is System.arraycopy?
System.arraycopy is a native method (written in optimized C/C++ code) that efficiently copies elements from one array to another. It's the engine behind ArrayList's reallocation process.
Signature:
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
src— the source array (the old, full array)srcPos— starting position in the source (usually 0)dest— the destination array (the new, larger array)destPos— starting position in the destination (usually 0)length— how many elements to copy
The Reallocation Process
When ArrayList triggers a capacity expansion (remember the 1.5x growth strategy?), here's what happens:
- Allocate a new array with the expanded capacity
- Copy all existing elements using
System.arraycopy - Replace the internal reference to point to the new array
- Discard the old array (garbage collected)
Why System.arraycopy?
This native method is highly optimized, often using block memory operations at the hardware level. It's much faster than manually looping through elements with for loops.
Analogy: It's like using a moving truck instead of carrying items one-by-one between houses—bulk transfer is always more efficient.
Key Takeaway: System.arraycopy is the low-level mechanism that physically moves elements from a full array to a newly allocated, larger one during ArrayList capacity expansion, making reallocation as fast as possible.