In: Computer Science
I am not quite sure how to get this program working or how to start it in the first place.
Write a full Java program and do the following:
1- Create a generic class and declare a one dim array as a private member.
2- Add a constructor to initialize the array.
3- A set method to set the array.
4- Sort method to sort the array.
5- Print method to print the array.
6- Reverse method to reverse the array recursively.
// ArrayOperation.java : Java program to create a generic class that consists of types that are comparable (for sorting)
public class ArrayOperation<T extends Comparable<T>> {
private T array[];
// constructor that initializes the array to input argument inArray
public ArrayOperation(T inArray[])
{
array = (T[])new Comparable[inArray.length];
for(int i=0;i<inArray.length;i++)
array[i] = inArray[i];
}
// method to the array to inArray
public void set(T inArray[])
{
array = (T[])new Object[inArray.length];
for(int i=0;i<inArray.length;i++)
array[i] = inArray[i];
}
// method to sort the elements of array
public void sort()
{
int min;
for(int i=0;i<array.length-1;i++)
{
min = i;
for(int j=i+1;j<array.length;j++)
{
if(array[j].compareTo(array[min]) < 0)
min = j;
}
if(i != min)
{
T temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
}
// method to display the array
public void show()
{
for(int i=0;i<array.length;i++)
System.out.println(array[i]);
}
// method to reverse the array
public void reverse()
{
for(int i=0,j=array.length-1;i<array.length/2;i++,j--)
{
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
public static void main( String[] args)
{
// test the class methods
Integer array[] = {21,15,20,12,7,10,6,5,17};
ArrayOperation<Integer> obj = new ArrayOperation<>(array);
System.out.println("Initial array : ");
obj.show();
obj.sort();
System.out.println("Sorted array : ");
obj.show();
System.out.println("Reversed array : ");
obj.reverse();
obj.show();
}
}
//end of program
Output: