Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

hi, I have an interface which has a method that returns the index of smallest el

ID: 3752134 • Letter: H

Question

hi, I have an interface which has a method that returns the index of smallest element in the array.

the interface has <T extends Comparable <T> and the method returnes int (int min () )

in the class of implemention has an generic array which defiend like this:

T Myarray[];
       Myarray = (T[]) new Comparable[size];
# note : note sure if this way best way to create generic array

My question is how i can make the min method work for the generic array to make comparison, since every time it gives me an error:
at java.lang.Integer.compareTo(Unknown Source),
and how i can initialize the generic array in the main class with one parameter(the size).

Explanation / Answer

Please find the generic implementation of min() method below.

CODE

===================

T min (int size) {

T min = Myarray[0];

for(int i=1; i<size; i++) {

if(min.compareTo(Myarray[i]) > 0) {

min = Myarray[i];

}

}

return min;

}

And, ideally in main class, you should not create a genric array. Instead, you should always create an array of specific data type. For example, you can create an Integer array as below.

Integer arr[] = {34, 56, -9, 56};

And, then while creating an instance of your class, you should replace <T> with <Integer> and then call the min() on it.