Java中的泛型:我如何使这个例子有效?

时间:2012-08-09 12:09:48

标签: java generics

class main{
 public static void main(String[] args){
  int[] array = new int[3];
  array[0]=3;
  array[1]=2;
  array[2]=1;
  System.out.println(<Integer>countGreaterThan(array,1));
 }
 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;
 }
}

我在Java Documentation中得到了这个例子。当我编写扩展Comparable时,我怎么能告诉编译器什么是类型? 我想我应该在<T extends Comparable<T>>中实例化T,但是如何?

4 个答案:

答案 0 :(得分:7)

只需将int更改为Integer,然后在打印声明中删除那个丑陋的<Integer>

Integer[] array = new Integer[3];
array[0] = 3;
array[1] = 2;
array[2] = 1;
System.out.println(countGreaterThan(array, 1));

答案 1 :(得分:2)

我会安排这个,所以你可以使用varargs

static <T extends Comparable<T>> int countGreaterThan(T elem, T... anArray) {
    int count = 0;
    for (T e : anArray)
        if (e.compareTo(elem) > 0)
            ++count;
    return count;
    }
}

System.out.println(countGreaterThan(1, 3,2,1));

答案 2 :(得分:0)

class main {
    public static void main(String[] args){
  Integer[] array = new Integer[3];
  array[0]=3;
  array[1]=2;
  array[2]=1;
  System.out.println(countGreaterThan(array,1));
 }

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

答案 3 :(得分:0)

Integer[] array = new Integer[3];   
    array[0]=3;   
    array[1]=2;   
    array[2]=1;   
    System.out.println(countGreaterThan(array,1));  

这是你在找什么?