简体   繁体   中英

Why my Java code cannot compile? [Java: Generic Methods and Bounded Type Parameters]

The following is my Java code and it just cannot compile. I cannot figure the reason for fail:

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

It doesn't compile and the error is:

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

I happened because your method1 method using custom Comparable Interface where Integer uses java.lang.Comparable , so method1 will throw exception.

Use only below code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM