2. This problem asks you to write a generic method, and call it. Write a generic
ID: 3701210 • Letter: 2
Question
2. This problem asks you to write a generic method, and call it. Write a generic method printBackwards which receives an array of any type and prints the array elements backwards (from end to start). You can place the method inside of the provided class ArrayStuff. (a) (b) Create two arrays, one of a primitive value [hint: use a wrapper class] and another of Strings, and call your generic method. public class ArrayStuff public static void main (String [ arg) // Your generic method goes here / ArrayStuffExplanation / Answer
(A)
public void printBackwards(E[] arr)
{
int i;
// traverse array in reverse order
for( i = arr.length - 1 ; i >= 0 ; i-- )
System.out.println(arr[i]);
}
(b)
public class ArrayStuff<E>
{
public void printBackwards(E[] arr)
{
int i;
// traverse array in reverse order
for( i = arr.length - 1 ; i >= 0 ; i-- )
System.out.println(arr[i]);
}
public static void main(String args[])
{
ArrayStuff<Integer> ob1 = new ArrayStuff<Integer>();
int[] arr1 = new int[10];
int i;
for( i = 0 ; i < 10 ; i++ )
arr1[i] = i + 1;
Integer[] arr = new Integer[10];
// copy contents of arr1 to arr
for( i = 0 ; i < 10 ; i++ )
arr[i] = Integer.valueOf(arr1[i]);
ob1.printBackwards(arr);
ArrayStuff<String> ob2 = new ArrayStuff<String>();
String[] arr2 = { "My", "name", "is", "Chandler", "Bing" };
ob2.printBackwards(arr2);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.