1

I am learning generic methods in Java. I want to count number of elements of an array greater than a given number. Here is my code:

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

    public static <T extends Comparable<T>> int countGreaterThan(T[] list, T element){
        int count = 0;
        for(T e:list){
            if (e.compareTo(element)>0){
                ++count;
            }
        }
        return count;
    }

    public static void main(String[] args){
        Integer[] intArray = {5 ,10,8,1,0,3};
        Integer u = new Integer(5);
        System.out.print("Number of elements are greater than "+ u.toString()+" is:");
        System.out.print(countGreaterThan(intArray,u));
    }
}

I got error "countGreaterThan is not applicable for the arguments (Integer[],Integer)". How could I change my code?

Thanks.

Tuan Ng
  • 149
  • 1
  • 1
  • 6
  • why do you need Comparable interface defined in your class? There is already one in java APIs – sidgate Dec 30 '15 at 06:57
  • Apart from your actual problem, instead of new Integer(5), use Integer.valueOf(5). http://stackoverflow.com/questions/2974561/new-integer-vs-valueof – Somnath Musib Dec 30 '15 at 06:59

2 Answers2

1

You shouldn't write Comparable interface by yourself, it's the default Java interface from java.lang package (you don't even have to import in manually). Remove your interface declaration inside class and it will work:

public class GenericMethodExample {

    public static <T extends Comparable<T>> int countGreaterThan(T[] list, T element){
        int count = 0;
        for(T e:list){
            if (e.compareTo(element)>0){
                ++count;
            }
        }
        return count;
    }

    public static void main(String[] args){
        Integer[] intArray = {5 ,10,8,1,0,3};
        Integer u = new Integer(5);
        System.out.print("Number of elements are greater than "+ u.toString()+" is:");
        System.out.print(countGreaterThan(intArray,u));
    }
}
coolguy
  • 3,011
  • 2
  • 18
  • 35
1

Your method countGreaterThan is for types that extends your own Comparable interface. Integer doesn't but extends the build in java.lang.Comparable interface. So remove your interface and it works or use it with an own class that extends your interface.

ArcticLord
  • 3,999
  • 3
  • 27
  • 47