Generic Operations

Create a JAVA program using Generics that will accept a user defined type parameter when called, that then performs two different operations on the object created.  The first operation must be in O(n) time, and the second operation must be in O(n2) time.

Solution

public class GenericMethodTest {

// generic method printArray O(n)

public static < E > void printArray( E[] inputArray ) {

// Display array elements

for(E element : inputArray) {

System.out.printf(“%s “, element);

}

System.out.println();

}

 

// generic method sort Array O(n^2)

public static <E extends Comparable<E>> void sortArray(E[] inputArray) {

for(int i=0;i<inputArray.length;i++){

for(int j=i+1;j<inputArray.length;j++){

E max=maximum(inputArray[i],inputArray[j]);

if(max.equals(inputArray[i])){

inputArray[i]=inputArray[j];

inputArray[j]=max;

}

}

}

printArray(inputArray);

}

 

public static <E extends Comparable<E>> E maximum(E x, E y) {

E max = x;   // assume x is initially the largest

if(y.compareTo(max) > 0) {

max = y;   // y is the largest so far

}

return max;   // returns the largest object

}

 

public static void main(String args[]) {

// Create arrays of Integer, Double and Character,String

Integer[] intArray = { 5, 4, 3, 1, 2 };

Double[] doubleArray = { 5.1, 2.2, 3.4, 1.4 };

Character[] charArray = { ‘H’, ‘E’, ‘L’, ‘L’, ‘O’ };

String[] stringArray={“sadsd”,”dasafe”,”4rrwe”,”mkvg”};

System.out.println(“Array integerArray contains:”);

printArray(intArray);

System.out.println(“Sorted integerArray contains:”);

sortArray(intArray);

System.out.println(“\nArray doubleArray contains:”);

printArray(doubleArray);

System.out.println(“Sorted doubleArray contains:”);

sortArray(doubleArray);

System.out.println(“\nArray charArray contains:”);

printArray(charArray);

System.out.println(“Sorted charArray contains:”);

sortArray(charArray);

System.out.println(“\nArray stringArray contains:”);

printArray(stringArray);

System.out.println(“Sorted stringArray contains:”);

sortArray(stringArray);

}

}