Hello I am writing this program, and I am trying to figure out how to compare two items in an array to find the largest item.
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]>a[i+1])
arrCopy[i]=a[i];
else
arrCopy[i]=a[i+1];
}
return arrCopy[0];
}
But then I don't know how to test for it, I tried :
T[] a = {1,12,7,45,22,23,5};
System.out.println("Array: [1,12,7,45,22,23,5] low=0 high, Largest?: " + rec.getLargest(a, 0, 6));
but I get an error message
The method getLargest(T[], int, int) in the type Rec is not applicable for the arguments (int[], int, int)
How do I call it to make it an array of numbers? Would an array of strings work with the code I have for getting the largest?
Maybe is just simple answers but I've been working on the whole program for a while and things don't look so clear now.
EDIT
After changing the array from int[] to Integer[]. I am getting an error on this line if(a[i]>a[i+1])
saying
The operator > is undefined for the argument type(s) T, T
I'm assuming I would have to change the >
sign to compare elements in the array, but how do I do this? Use compareTo() ?
It's not working because int
isn't a subclass of Comparable
because it's not even an Object
. Basically, you can't use primitives ( int
, short
, long
, char
, boolean
, byte
) with generics.
Try calling it with an array of Integer
.
Integer[] a = {1,12,7,45,22,23,5};
System.out.println("Array: [1,12,7,45,22,23,5] low=0 high, Largest?: " + rec.getLargest(a, 0, 6))
If you want your method to be able to accept int[]
, you'll need to have a separate function for each one you want to accept ( int getLargest(int[], int, int)
, char getLargest(char[], int, int)
, etc.).
EDIT:
In response to your edit, you need to use compareTo()
. <
is only defined for primitives.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.