Junior — Middle
Can you explain how array element copying is performed and what methods exist for array cloning?
sobes.tech AI
Answer from AI
In Java, copying array elements can be done in several ways:
- For loop — the simplest way, manually copying elements one by one:
int[] source = {1, 2, 3};
int[] dest = new int[source.length];
for (int i = 0; i < source.length; i++) {
dest[i] = source[i];
}
System.arraycopymethod — a more efficient way to copy blocks of an array:
int[] source = {1, 2, 3};
int[] dest = new int[source.length];
System.arraycopy(source, 0, dest, 0, source.length);
clone()method — creates a shallow copy of the array:
int[] source = {1, 2, 3};
int[] dest = source.clone();
Arrays.copyOfmethod — a convenient way to copy with the ability to change the size:
import java.util.Arrays;
int[] source = {1, 2, 3};
int[] dest = Arrays.copyOf(source, source.length);
All these methods create a shallow copy of the array, meaning for primitive type arrays, the values are copied, and for object arrays, the references to objects are copied.