-3

I have tried many ways to call the countGreaterThan() function (described here), but I am unable to get it to work. I understand I need to use Integer instances and not primitives. This is what I've tried:

MainClass.java

public class MainClass {

public 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;
}

public static void main(String[] args){
    Integer[] myArray = {0,1,2,3,4};
    Integer myInt = new Integer(2);
    int result = countGreaterThan(myArray,myInt);
            System.out.println(result);
}
}

This is the interface Comparable.java

public interface Comparable<T> {
   public int compareTo(T o);
}

And this is the error I get -

Bound mismatch: The generic method countGreatherThan(T[],T) of type MainClass is not applicable for the arguments(Integer[],Integer). The inferred type Integer is not a valid subsitute for the bounded parameter >

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

2 Answers2

1

If I understand your question, it appears like you are calling countGreaterThan()! What you aren't doing is printing the result, or saving the result.

countGreaterThan(myArray,myInt);

Should be

int result = countGreaterThan(myArray, myInt);
System.out.println(result);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

I have to wonder if you've created your own Comparable.java interface and are using it. If so, you're seeing your error because Integer is not using your interface, but rather the one that is part of core Java. If so, get rid of your Comparable.java class, delete it, and just use the one that is part of core Java. No need to import as it is part of the java.lang package, a package whose classes are all automatically imported by default.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • @user3745246: Sorry for annoying you to improve your question, but note that we could only figure this out after you did your improvents. Thanks for the improvements and you're welcome for the answer. – Hovercraft Full Of Eels Jun 28 '14 at 21:17