Write a
generic program to reverse elements of an array.
import java.util.Objects; public class ArrayReverse { public static <T> void reverseArray(T arr[]) { Objects.nonNull(arr); reverse(arr, 0, arr.length - 1); } private static <T> void reverse(T arr[], int start, int end) { if (start > end) return; T temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; reverse(arr, ++start, --end); } }
Following is
the junit test case for above application.
import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.junit.Test; public class ArrayReverseTest { @Test public void test1() { Integer arr1[] = { 1, 2, 3, 4, 5, 6 }; Integer expected1[] = { 6, 5, 4, 3, 2, 1 }; Integer arr2[] = { 1, 2, 3, 4, 5, 6, 7 }; Integer expected2[] = { 7, 6, 5, 4, 3, 2, 1 }; Integer arr3[] = { 1 }; Integer expected3[] = { 1 }; ArrayReverse.reverseArray(arr1); ArrayReverse.reverseArray(arr2); ArrayReverse.reverseArray(arr3); assertTrue(Arrays.equals(arr1, expected1)); assertTrue(Arrays.equals(arr2, expected2)); assertTrue(Arrays.equals(arr3, expected3)); } }
No comments:
Post a Comment