Concepts: Generics Arrays Objects Part I: Write a routine in Java that takes an
ID: 3909355 • Letter: C
Question
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.
Submission:
The code and screenshots that demonstrate that you completed Part I and Part II.
Project files and Word document with pasted code and screenshots.
Explanation / Answer
Dear Student,
Please find the codes below :
//Solution 1
class ArraySearch<E> {
public int find (E[] array, E item) {
int index = -1;
for (int i = 0; i < array.length; i++) {
if (array[i].equals(item)) {
System.out.println("There is a element " + array[i] +
" at index " + i);
index = i;
break;
}
}
return index;
}
}
public class ArraySearchRunner {
public static void main(String[] args) {
String[] strings = new String[]{"Jim", "Tim", "Bob", "Greg"};
Integer[] ints = new Integer[]{1, 2, 3, 4, 5};
ArraySearch arrSearch= new ArraySearch();
arrSearch.find(strings, "Bob");
arrSearch.find(ints, 4);
}
}
Sample Output :
There is a element Bob at index 2
There is a element 4 at index 3
//Solution 2:
class Greater<E1,E2>{
public int compare(E1 obj1, E2 obj2) {
Integer i1 = (Integer)obj1;
Integer i2 = (Integer)obj2;
if(i1 > i2)
return i1;
else if(i1 < i2)
return i2;
return 0;
}
}
public class GreaterThan {
public static void main(String[] args) {
Integer i1 = new Integer(10);
Integer i2 = new Integer(20);
Greater grt= new Greater();
System.out.println(grt.compare(i1,i2));
}
}
Sample output :
20
If you like this answer, give a thumbs up! happy learning :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.