2014-12-30 78 views
0

虽然学习Java的泛型参数化,我想出了这个代码:调用参数化方法

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

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

我想测试它,所以我写了这个:

Integer[] iArray = new Integer[10]; 
for (int i=0; i<10; i++){ 
    iArray[i] = new Integer(i); 
} 

int a = countGreaterThan(iArray, Integer.valueOf(5)); 

但是编译器是给我的错误调用方法countGreaterThan当最后一行信息:

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

我失去了一些东西明显?

回答

5

java.lang.Integer没有实现您刚刚编写的Comparable接口。

您应该删除该接口并使用它实现的内置接口。

+0

噢,真的... 这是愚蠢的例子,我发现... 谢谢! – ajuric