class main{
public static void main(String[] args){
int[] array = new int[3];
array[0]=3;
array[1]=2;
array[2]=1;
System.out.println(<Integer>countGreaterThan(array,1));
}
static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
}
I got this examle in Java Documentation. When i write extends Comparable, how can i tell the compiler what is type?
I think i should instantiate T in <T extends Comparable<T>>, but how?
Just change the int to Integer and remove that ugly <Integer> inside your print statement.
Integer[] array = new Integer[3];
array[0] = 3;
array[1] = 2;
array[2] = 1;
System.out.println(countGreaterThan(array, 1));
I would arrange this so you can use varargs
static <T extends Comparable<T>> int countGreaterThan(T elem, T... anArray) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
}
System.out.println(countGreaterThan(1, 3,2,1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With