Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics - inserting inner type parameter

Tags:

java

generics

I am new to java. I am just trying to pass Comparable<String> into a method parameter of generic type <E extends Comparable<E>> . I believe the meaning of <E extends Comparable<E>> is any object that extends Comparable. Please let me know how to pass Comparable<String> or any object that extends Comparable<String> and has an other object in it.

Compiler is giving me error The inferred type Compare<String> is not a valid substitute for the bounded parameter <E extends Comparable<E>>

Code:

public class Compare<T> implements Comparable<T>{

    public int compareTo(T o) {

        return 0; // Not worried about logic

    }

}

class CompareTest{

    public <E extends Comparable<E>>void testGeneric(E e){

        System.out.println("Executed");
    }

    public static void main(String args[]){
        Compare<String> compare = new Compare<String>();

        CompareTest test = new CompareTest();
        test.testGeneric(compare);
        //The inferred type Compare<String> is not a valid substitute for the bounded
        //parameter <E extends Comparable<E>>
    }
}
like image 428
Mr A Avatar asked Sep 10 '26 14:09

Mr A


2 Answers

E extends Comparable<E> means: a type E that is able to compare to other objects of the same type E.

But your Compare type doesn't qualify. It can't compare with another Compare. A Compare<T> can only compare itself to a T, and not to a Compare<T>, since it's declared as

public class Compare<T> implements Comparable<T>

It's quite hard to understand what you want to achieve with this Compare type.

like image 120
JB Nizet Avatar answered Sep 12 '26 04:09

JB Nizet


Your method

public <E extends Comparable<E>> void testGeneric(E e){

expects a type E that is a sub type of Comparable<E>. But you are passing it a Compare<String> which is not a sub type of <Comparable<Compare<String>>, but a sub type of Comparable<String>.

You'll have to clarify what you are trying to do if you need more help.

like image 21
Sotirios Delimanolis Avatar answered Sep 12 '26 03:09

Sotirios Delimanolis