Program to replicate array in java
Arrays are a fundamental data structure that allows you to store multiple values of the same type in a single variable. Sometimes, you may need to replicate an array, either to create a copy or to repeat its elements multiple times. Below are the common methods for replicating arrays in Java:
- Shallow Copy: Copying the array such that the new array references the same objects as the original.
- Deep Copy: Copying the array and creating new instances of the objects.
- Array Replication: Repeating the entire array a specified number of times to create a new larger array.
Array Replication (Repeat the Array)
import java.util.Arrays; public class ArrayReplication { public static void main(String[] args) { int[] originalArray = {1, 2, 3, 4, 5}; int repeatCount = 3; // Number of times to repeat the array int[] replicatedArray = new int[originalArray.length * repeatCount]; for (int i = 0; i < repeatCount; i++) { System.arraycopy(originalArray, 0, replicatedArray, i * originalArray.length, originalArray.length); } System.out.println("Original Array: " + Arrays.toString(originalArray)); System.out.println("Replicated Array: " + Arrays.toString(replicatedArray)); } }
Output:
Original Array: [1, 2, 3, 4, 5] Replicated Array: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
Explanation:
In Java, replicating an array means creating a new array with the same elements as an existing one. This can be done by iterating through the original array and copying each element to the new array. Java provides several ways to achieve this, including using a loop, the 'System.arraycopy()'
method, or the 'Arrays.copyOf()'
method from the 'java.util.Arrays'
class.