Home > Software design >  (Java) Return generic T array index as int after passed into an int function?
(Java) Return generic T array index as int after passed into an int function?

Time:10-07

I had this 4-part Pset for a class (submission deadline already passed), but I've been dying on problem 1 and the next set Pset is going to be open later this week. I've read the HW chapters, gone to office hours (they can help the concept with but can't help with implementing code) and rewatched lectures, but I can't find how I'm supposed to do this.

This is the part that I can't change (import java.util.* is included above it):

  public static <T extends Comparable<T>> int findMax(T[] arr)

So it's an int function that passes a type T array and is supposed to return an int index. I tried a number of ways to try iterating using for & while loops, but the problem is I can't figure out how to do it.

This code below is modified from programmer/blogger Deepesh Darshan's post on finding max values using generics, as it was really similar to one of mine that used a for loop. the "return -1;" is in case no code was added.

          int maxPoint = arr[0];
      for(T arrScan : arr){
          if(arrScan.compareTo(maxPoint) > 0 ) {
            maxPoint = arrScan;
          }
              return maxPoint; 
      }
     return -1;
  }
    

One issue is his solution uses T the whole way through and mine can't.

public static <T extends Comparable<T>> T max(T... elements)

My code above gives the following errors:

GenericMethods.java:16: error: incompatible types: T cannot be converted to int
        int maxPoint = arr[0];
                          ^
  where T is a type-variable:
    T extends Comparable<T> declared in method <T>findMax(T[])
GenericMethods.java:18: error: incompatible types: int cannot be converted to T
          if(arrScan.compareTo(maxPoint) > 0 ) {
                               ^
  where T is a type-variable:
    T extends Comparable<T> declared in method <T>findMax(T[])
GenericMethods.java:19: error: incompatible types: T cannot be converted to int
            maxPoint = arrScan;
                       ^
  where T is a type-variable:
    T extends Comparable<T> declared in method <T>findMax(T[])
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors

I know it's because I'd need to make maxPoint "T", not "int", but that just kicks the conversion error down to the return value.

Is there some reading or advice someone could point me to on how to find the max index with the given restrictions without causing conversion errors? I can't seem to find any on GFG, W3 or any of the places suggested to me.

CodePudding user response:

You need to track the index instead of the element:

int max = 0;
for (int i = 1; i < arr.length; i  ) {
    if (arr[i].compareTo(arr[max]) > 0) {
        max = i;
    }
}
return max;
  • Related