import java.util.Arrays;
public class ArraySync {
/**
* Synchronizes the resources of two arrays. Handles resizing and copying.
* @param sourceArray The array to copy from.
* @param destinationArray The array to copy to.
* @return The destination array with the synchronized resources. Returns null if either input is null.
* @throws IllegalArgumentException if arrays have different lengths.
*/
public static <T> T[] syncArrays(T[] sourceArray, T[] destinationArray) {
if (sourceArray == null || destinationArray == null) {
return null; // Handle null input
}
if (sourceArray.length != destinationArray.length) {
throw new IllegalArgumentException("Arrays must have the same length.");
}
// Copy elements from source to destination
System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);
return destinationArray;
}
/**
* Synchronizes the resources of two arrays with automatic resizing.
* @param sourceArray The array to copy from.
* @param destinationArray The array to copy to.
* @return The destination array with synchronized resources.
* @throws IllegalArgumentException if source array is larger than destination.
*/
public static <T> T[] syncArraysResize(T[] sourceArray, T[] destinationArray) {
if (sourceArray == null || destinationArray == null) {
return null;
}
if (sourceArray.length > destinationArray.length) {
throw new IllegalArgumentException("Source array cannot be larger than destination array.");
}
// Copy elements from source to destination, resizing if needed.
System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);
return destinationArray;
}
public static void main(String[] args) {
Integer[] arr1 = {1, 2, 3};
Integer[] arr2 = new Integer[3];
Integer[] syncedArr = syncArrays(arr1, arr2);
System.out.println(Arrays.toString(syncedArr)); // Output: [1, 2, 3]
String[] arr3 = {"a", "b"};
String[] arr4 = new String[5];
String[] syncedArrResize = syncArraysResize(arr3, arr4);
System.out.println(Arrays.toString(syncedArrResize)); //Output: [a, b, null, null, null]
}
}
Add your comment