为什么我的Java代码无法编译? [Java:通用方法和有界类型参数]

时间:2015-10-09 10:23:02

标签: java generic-method bounded-types

以下是我的Java代码,它无法编译。我无法想出失败的原因:

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


class MyClass {
    public static  <T extends Comparable<T>> int method1(T t1, T t2)
    {
        return t1.compareTo(t2);
    }
}

class TestApp1 {
    public static void main(String[] args) {
        Integer p1 =new Integer(8);
        Integer p2 =new Integer(9);

        int result = MyClass.method1(p1,p2);

        System.out.println("result = " + result);
    }
}

它没有编译,错误是:

TestApp1.java:19: error: method method1 in class MyClass cannot be applied to given types;
        int result = MyClass.method1(p1,p2);
                            ^   required: T,T   found: Integer,Integer   reason: inferred type does not conform to upper bound(s)
    inferred: Integer
    upper bound(s): Comparable<Integer>   where T is a type-variable:
    T extends Comparable<T> declared in method <T>method1(T,T) 1 error

1 个答案:

答案 0 :(得分:4)

我之所以发生,是因为您的method1方法使用自定义Comparable接口,其中整数使用java.lang.Comparable,因此method1会抛出异常。

仅在代码下方使用:

class MyClass {
    public static  <T extends Comparable<T>> int method1(T t1, T t2)
    {
        return t1.compareTo(t2);
    }
}

class TestApp1 {
    public static void main(String[] args) {
        Integer p1 =new Integer(8);
        Integer p2 =new Integer(9);

        int result = MyClass.method1(p1,p2);

        System.out.println("result = " + result);
    }
}