COP 3337 SECTION U05 Spring 2017 The Use of java.lang.reflect.Array ================================== I. The Program -------------- import java.lang.reflect.Array; public class UsingReflectArray { public static void main(String[] args) { System.out.println("Testing append"); System.out.println("==============\n\n"); // test 1 System.out.println("a1 = { 1, 3, 5, 7}"); System.out.println("a2 = { 2, 4, 6}"); Integer[] a1 = { 1, 3, 5, 7}; Integer[] a2 = {2, 4, 6}; System.out.println("We append a2 at the end of a1."); Integer[] a3 = append(a1,a2); write("The resulting array", a3); // test 2 System.out.println("Another test"); System.out.println("list1 = { Bill, Mark, Geoff, Peter}"); System.out.println("list2 = { Christine, Radu, Raju}"); String[] list1 = { "Bill", "Mark", "Geoff", "Peter"}; String[] list2 = {"Christine", "Radu", "Raju"}; System.out.println("We append list2 at the end of list1."); String[] list3 = append(list1,list2); write("The resulting list", list3); } // return the array obtained by appending arr2 at the end of arr1 // if either array is null throw a null pointer exception public static T[] append(T[] arr1, T[] arr2) { if (arr1 == null || arr2 == null) throw new NullPointerException("null array(s)"); // generate the out array T[] out = (T[]) Array.newInstance(arr1.getClass().getComponentType(), arr1.length + arr2.length); // copy the 2 arrays System.arraycopy(arr1,0,out,0,arr1.length); System.arraycopy(arr2, 0, out, arr1.length, arr2.length); return out; } // print an array public static void write(String name, T[] arr) { if (arr == null) { System.out.println(name + " is null."); } else if (arr.length == 0) { System.out.println(name + " is empty."); } else // arr has items { System.out.println("The contents of " + name + ":"); for (T item : arr) System.out.println(item); System.out.println(); // empty line } } } II. The Output: --------------- run: Testing append ============== a1 = { 1, 3, 5, 7} a2 = { 2, 4, 6} We append a2 at the end of a1. The contents of The resulting array: 1 3 5 7 2 4 6 Another test list1 = { Bill, Mark, Geoff, Peter} list2 = { Christine, Radu, Raju} We append list2 at the end of list1. The contents of The resulting list: Bill Mark Geoff Peter Christine Radu Raju BUILD SUCCESSFUL (total time: 0 seconds)