I am trying to figure out how to compare two items within a T[] array, here is what I have:
public static <T extends Comparable< ? super T>> T getLargest(T [] a, int low,
int high){
if(low>high)
throw new IllegalArgumentException();
T[] arrCopy = (T[]) new Object[high-low];
for(int i=low;i<high;i++){
if(a[i].compareTo(a[i-1])>0)
arrCopy[i]=a[i];
else
arrCopy[i]=a[i+1];
}
return arrCopy[0];
}
and then I get the error: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
Any ideas on how I can resolve this?
You can assign the array like this:
Although the unchecked warning is necessary, this should actually be safe.
Btw, if you want to find the largest element in an array, here’s a oneliner:
For the complete problem you can use one of these two (they are equivalent):