1. import java.util.Arrays;
  2. public class ArraySync {
  3. /**
  4. * Synchronizes the resources of two arrays. Handles resizing and copying.
  5. * @param sourceArray The array to copy from.
  6. * @param destinationArray The array to copy to.
  7. * @return The destination array with the synchronized resources. Returns null if either input is null.
  8. * @throws IllegalArgumentException if arrays have different lengths.
  9. */
  10. public static <T> T[] syncArrays(T[] sourceArray, T[] destinationArray) {
  11. if (sourceArray == null || destinationArray == null) {
  12. return null; // Handle null input
  13. }
  14. if (sourceArray.length != destinationArray.length) {
  15. throw new IllegalArgumentException("Arrays must have the same length.");
  16. }
  17. // Copy elements from source to destination
  18. System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);
  19. return destinationArray;
  20. }
  21. /**
  22. * Synchronizes the resources of two arrays with automatic resizing.
  23. * @param sourceArray The array to copy from.
  24. * @param destinationArray The array to copy to.
  25. * @return The destination array with synchronized resources.
  26. * @throws IllegalArgumentException if source array is larger than destination.
  27. */
  28. public static <T> T[] syncArraysResize(T[] sourceArray, T[] destinationArray) {
  29. if (sourceArray == null || destinationArray == null) {
  30. return null;
  31. }
  32. if (sourceArray.length > destinationArray.length) {
  33. throw new IllegalArgumentException("Source array cannot be larger than destination array.");
  34. }
  35. // Copy elements from source to destination, resizing if needed.
  36. System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);
  37. return destinationArray;
  38. }
  39. public static void main(String[] args) {
  40. Integer[] arr1 = {1, 2, 3};
  41. Integer[] arr2 = new Integer[3];
  42. Integer[] syncedArr = syncArrays(arr1, arr2);
  43. System.out.println(Arrays.toString(syncedArr)); // Output: [1, 2, 3]
  44. String[] arr3 = {"a", "b"};
  45. String[] arr4 = new String[5];
  46. String[] syncedArrResize = syncArraysResize(arr3, arr4);
  47. System.out.println(Arrays.toString(syncedArrResize)); //Output: [a, b, null, null, null]
  48. }
  49. }

Add your comment