Search code examples
javaarraysgenericscomparable

How to pass an array to a type parameter bounded by the Comparable interface


I have an interface:

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

that bounds a type parameter in the method

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

How can I pass the method properCountGreaterThan(T [] tArray, T elem) an array of integers, and the integer I want the elements of the array to be compared too? I recently learned about the Compare interface in in this tutorial but it does not explain how to use it to actually count the number of elements in a array that are greater than a specified element, and by that I mean it does not explain how to invoke the method and pass it an array and the specified element. I also do not understand how the method properCountGreaterThan would compare a specified element to elements of a array since the method compareTo(T o) has no implementation and when it is called in properCountGreaterThan it is only being compared to 0:

if (e.compareTo(elem) > 0) { count ++; }

Solution

  • you can pass the object to that method like this.

    public static void main (String[] args)  {
    
        int num = countGreaterThan(new Integer[] {25,14,48,86}, 20);
    }
    
    
    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;
    }
    

    method says it can accept anything that implements Comparable interface. Integer class does implement Comparable. to understand better you have to read more about Generics Angelika Langer explains it best, at list for me.