Of course! Let's dive deep into Arrays.copyOf() in Java.

What is Arrays.copyOf()?
Arrays.copyOf() is a static utility method in the java.util.Arrays class. Its primary purpose is to create a new array and copy elements from an existing array into it. It's a convenient and safe way to resize or duplicate an array.
The Method Signature
The method has several overloaded versions to handle different primitive and object array types. The core idea is the same for all:
// For object arrays public static <T> T[] copyOf(T[] original, int newLength) // For primitive arrays (examples) public static int[] copyOf(int[] original, int newLength) public static double[] copyOf(double[] original, int newLength) // ... and so on for byte, short, long, float, char, boolean
Parameters:
original: The source array from which elements will be copied.newLength: The length of the new array to be created.
Return Value:

- A new array of the same type as the
originalarray. - The new array's length is equal to
newLength.
How It Works: The Rules of Copying
The behavior of Arrays.copyOf() depends on the relationship between the original array's length and the newLength you specify.
Case 1: newLength is greater than the original array's length
- A new, larger array is created.
- All elements from the original array are copied to the new array.
- The extra space in the new array is filled with default values.
- For object arrays:
null - For
intarrays:0 - For
booleanarrays:false - For
chararrays:'\u0000'(null character)
- For object arrays:
Case 2: newLength is equal to the original array's length
- A new array of the same size is created.
- All elements from the original array are copied to the new array.
- This is effectively a shallow copy of the array.
Case 3: newLength is less than the original array's length
- A new, smaller array is created.
- The first
newLengthelements from the original array are copied to the new array. - The elements at the end of the original array are truncated and lost.
Code Examples
Let's see these cases in action with a simple String array.
import java.util.Arrays;
public class ArraysCopyOfExample {
public static void main(String[] args) {
String[] originalFruits = { "Apple", "Banana", "Cherry", "Date" };
System.out.println("Original Array: " + Arrays.toString(originalFruits));
// --- Case 1: newLength is GREATER than original length ---
// New array will be 6 elements long. The 5th and 6th will be null.
String[] largerArray = Arrays.copyOf(originalFruits, 6);
System.out.println("\nCase 1 (Larger): " + Arrays.toString(largerArray));
// Output: [Apple, Banana, Cherry, Date, null, null]
// --- Case 2: newLength is EQUAL to original length ---
// Creates a perfect copy.
String[] sameSizeArray = Arrays.copyOf(originalFruits, 4);
System.out.println("\nCase 2 (Same Size): " + Arrays.toString(sameSizeArray));
// Output: [Apple, Banana, Cherry, Date]
// --- Case 3: newLength is LESS than original length ---
// New array will be 2 elements long. "Cherry" and "Date" are lost.
String[] smallerArray = Arrays.copyOf(originalFruits, 2);
System.out.println("\nCase 3 (Smaller): " + Arrays.toString(smallerArray));
// Output: [Apple, Banana]
}
}
Important: Shallow Copy vs. Deep Copy
This is a crucial concept to understand when working with Arrays.copyOf().
-
Primitive Arrays (
int[],double[], etc.):Arrays.copyOf()always creates a deep copy. The primitive values are duplicated in the new array. Modifying one array has no effect on the other.
(图片来源网络,侵删)int[] original = {1, 2, 3}; int[] copy = Arrays.copyOf(original, 3); copy[0] = 99; System.out.println(Arrays.toString(original)); // Output: [1, 2, 3] System.out.println(Arrays.toString(copy)); // Output: [99, 2, 3] -
Object Arrays (
String[],MyClass[], etc.):Arrays.copyOf()creates a shallow copy. This means it copies the references to the objects, not the objects themselves.- A new array is created.
- The references from the original array are copied into the new array.
- Both arrays point to the exact same object instances.
Let's illustrate this with a custom class:
class Person { String name; Person(String name) { this.name = name; } @Override public String toString() { return name; } } public class ShallowCopyExample { public static void main(String[] args) { Person[] originalPeople = { new Person("Alice"), new Person("Bob") }; Person[] copyPeople = Arrays.copyOf(originalPeople, 2); System.out.println("Original: " + Arrays.toString(originalPeople)); System.out.println("Copy: " + Arrays.toString(copyPeople)); // Modify the object through the copied array copyPeople[0].name = "Alicia"; // The change is visible in the original array too! System.out.println("\nAfter modifying 'Alicia':"); System.out.println("Original: " + Arrays.toString(originalPeople)); // Output: [Alicia, Bob] System.out.println("Copy: " + Arrays.toString(copyPeople)); // Output: [Alicia, Bob] } }
If you need a deep copy for an object array (where you want new copies of the objects themselves), you must implement it manually, often with a loop and a copy constructor or a clone() method.
Arrays.copyOf() vs. System.arraycopy()
Arrays.copyOf() is implemented using System.arraycopy(). Here's how they compare:
| Feature | Arrays.copyOf() |
System.arraycopy() |
|---|---|---|
| Usage | Static method in java.util.Arrays |
Static method in java.lang.System |
| Purpose | Simple, high-level way to copy an entire array to a new one. | A low-level, high-performance utility for copying between any two arrays. |
| Destination | Implicitly creates a new array. | Requires you to provide a pre-existing destination array. |
| Parameters | (sourceArray, newLength) |
(source, srcPos, dest, destPos, length) |
| Flexibility | Less flexible. Copies from the start of the source array. | Highly flexible. Can copy any sub-range from the source to any sub-range in the destination. |
| Readability | More readable for simple, full-array copies. | More verbose, but gives you precise control over the copy operation. |
Example of System.arraycopy()
int[] source = {10, 20, 30, 40, 50};
int[] destination = new int[5]; // Must pre-allocate the destination array
// Copy 3 elements from source, starting at index 1,
// to destination, starting at index 2.
System.arraycopy(source, 1, destination, 2, 3);
// destination is now [0, 0, 20, 30, 40]
System.out.println(Arrays.toString(destination));
When to Use Arrays.copyOf()
Use Arrays.copyOf() when you want to:
- Resize an array: Easily make an array bigger (padding with defaults) or smaller (truncating).
- Duplicate an array: Create a new, independent copy of an array of the same size.
- Keep code simple and readable: For straightforward copying operations, it's much cleaner than
System.arraycopy().
Summary
Arrays.copyOf() is a fantastic, convenient tool in Java for array manipulation. Just remember its key characteristics:
- It always returns a new array.
- It handles resizing by padding with default values or truncating.
- For object arrays, it performs a shallow copy of the references.
- It's a user-friendly wrapper around the lower-level
System.arraycopy().
