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:
@SuppressWarnings("unchecked")
T[] arrCopy = (T[]) Array.newInstance(a.getClass().getComponentType(), high-low);
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:
public static <T extends Comparable<T>> T max(final T[] data) {
return Collections.max(Arrays.asList(data));
}
For the complete problem you can use one of these two (they are equivalent):
public static <T extends Comparable<T>> T maxA(final T[] data,int from, int to) {
return Collections.max(Arrays.asList(Arrays.copyOfRange(data, from, to)));
}
public static <T extends Comparable<T>> T maxB(final T[] data,int from, int to) {
return Collections.max(Arrays.asList(data).subList(from, to));
}