In: Computer Science
Java Programming Preferably
Concepts:
Generics
Arrays
Objects
Part I: Write a routine in Java that takes an array, the length of the array, and an element and returns the position of the element in the array. For example, given the array with values [2, 4, 6, 8] and element 6, the routine should return 2 (since counting from 0, 6 occurs at position 2 in the array). Your routine should use generics to enable your routine to be reusable for different element types. Be sure to test your code with a Java compiler before you submit it.
Part II: Write a generic “greater-than” function that (a) takes two objects as arguments, each of which has a “value” method which returns an integer; and (b) returns the argument whose “value” method returns the larger integer. Your generic function should constrain its type argument so that types without a “value” method cannot be used.Please review the test harness example to ensure your program meets the requirements. Find the test harness below;
public class TestGenerics {
public static void main(String[] args) {
MyFirstObject myObj1 = new MyFirstObject();
MySecondObject myObj2 = new MySecondObject();
MyGenerics mg = new MyGenerics();
Integer[] array = {2,4,6,8};
System.out.println( mg.partOne(array, array.length, 6) );
System.out.println( mg.partTwo(myObj1, myObj2) );
}
}
public class MyGenerics<T extends Comparable<T>>{
public int findPosition(T arr[] , int len, T target) {
for(int i=0 ; i<len; ++i) {
if(arr[i].compareTo(target)==0)
return i;
}
return -1;
}
public int greaterthan(Object o1, Object o2) {
MyFirstObject f1 = (MyFirstObject)o1;
MySecondObject f2 = (MySecondObject)o2;
if(f1.getValue() > f2.getValue())
return f1.getValue() ;
return f2.getValue() ;
}
}
============================================================
public class MyFirstObject{
int value;
MyFirstObject(int v){
this.value = v;
}
int getValue() {
return value;
}
}
===========================================
public class MySecondObject{
int value;
MySecondObject(int v){
this.value = v;
}
int getValue() {
return value;
}
}
===================================================
//Changed the function names, So please use this
public class TestGenerics {
public static void main(String[] args) {
MyFirstObject myObj1 = new MyFirstObject(10);
MySecondObject myObj2 = new MySecondObject(20);
MyGenerics mg = new MyGenerics();
Integer[] array = {2,4,6,8};
System.out.println( mg.findPosition(array, array.length, 6) );
System.out.println( mg.greaterthan(myObj1, myObj2) );
}
}
============================================================
SEE OUTPUT
Thanks, PLEASE COMMENT if there is any concern.