0

以下是我的 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
4

1 回答 1

4

我发生这种情况是因为您的method1方法使用Comparable了 Integer 使用的自定义接口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);
    }
}
于 2015-10-09T10:25:58.683 回答