Zander Hsu
Zander Hsu

Reputation: 49

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

Upvotes: 0

Views: 235

Answers (1)

Sumit Singh
Sumit Singh

Reputation: 15886

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

Upvotes: 4

Related Questions