Candice
Candice

Reputation: 21

The method countGreaterThan(T[], T) in the type GenericMethodsAndBoundedTypeParameters is not applicable for the arguments (Integer[], Integer)

Update:

This question came up while I was learning Java Generics from the Oracle Java Tutorials, the codes were from https://docs.oracle.com/javase/tutorial/java/generics/boundedTypeParams.html, and this led me to the following error. I didn't know that Java already has the Comparable interface at that time. Problem was solved right after I removed my own Comparable interface.

Original post:

I am having trouble fixing the error in the following code. I am using JavaSE-16 on Eclipse 2021-09

public class GenericMethodsAndBoundedTypeParameters {
    public static void main(String[] args) {
        int a = countGreaterThan(new Integer[] {1, 2, 3, 4, 5}, (Integer)(2));
    }
    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;
    }
}

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

The error message looks like this:

The method countGreaterThan(T[], T) in the type GenericMethodsAndBoundedTypeParameters is not applicable for the arguments (Integer[], Integer)

Upvotes: 1

Views: 35

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201439

Don't define your own Comparable interface. Also, you want ? super T. Like,

public static <T extends java.lang.Comparable<? super T>> int countGreaterThan(
            T[] anArray, T elem) {
    int count = 0;
    for (T e : anArray) {
        if (e.compareTo(elem) > 0) {
            ++count;
        }
    }
    return count;
}

Works for me. I get 3 when I add System.out.println(a); in the provided main.

Upvotes: 1

Related Questions