In: Computer Science
class ArrayReverse1{
public static void reverse(int[] a, int index) {
if (index >0)
{
index= index - 1; // Decrementing the index
System.out.printf("%d%n", a[index]);
reverse(a, index); // Recursive call
}
return;
}
public static void main (String args[])
{
int [] array = { 1, 2, 3, 4, 5 };
int n=array.length;
reverse(array,n); // function call
}
}
Write a generic version of the corrected recursive reverse method that could be used to print any of the following arrays (or arrays of other reference types) in reverse order.
Integer[] integerArray = {1,2,3,4,5,6};
Double[] doubleArray = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6};
String[] numbers = {"one", "two", "three", "four", "five", "six"};
Will the generic version of the reverse method (part (d)) work if the array is of type int? Explain your answer. Both generic and non-generic methods can be overloaded. The compiler performs a matching process to determine which method to call when a method is invoked. Under what circumstances does an attempt to make a match result in a compile-time error?
public class ArrayReverse1{
public static void main(String[] args) {
String[] names = { "hi", "you", "there" };
Integer[] a ={1,2,3,4};
Double[] d = {1.0,2.4,5.4};
reverse(names,names.length-1);
reverse(a,a.length-1);
reverse(d,d.length-1);
}
public static <T> void reverse(T[] array,int i) {
if(i<0){
System.out.println("");
return;
}
System.out.print(array[i] + " ");
reverse(array,i-1);
}
}