Search code examples
javagenericscomparable

Bound Mismatch : Generic class (of a Generic class extending Comparable (of a Generic class extending Comparable))


I know it sounds confusing, but that's the best I could explain. (You can suggest a better title). I have 3 classes:-

A

public class A <T extends Comparable<T>> {
    ...
}

B

public class B {
    A<C> var = new A<C>(); 
    // Bound mismatch: The type C is not a valid substitute for the bounded parameter <T extends Comparable<T>> of the type A<T>
    ...
}

C

public class C <T extends Comparable<T>> implements Comparable<C>{
    private T t = null;
    public C (T t){
        this.t = t; 
    }
    @Override
    public int compareTo(C o) {
        return t.compareTo((T) o.t);
    }
    ...
}

I am getting an error where I try to instantiate A in B

Bound mismatch: The type C is not a valid substitute for the bounded parameter < T extends Comparable < T > > of the type A


Solution

  • Thanks to the comments above @Boris the Spider

    The problem is that C is a raw type in B . Changed the instantiation to include the parameter (depending on the need)

    A< C<Integer> > var = new A< C<Integer> >();
    

    EDIT 1: Also, thanks to the comment below. A better practice is to change compareTo method in C to this,

    public int compareTo(C<T> o) {
        return t.compareTo(o.t);
    }
    

    EDIT 2: Also, there is a typo in the question (w.r.t. comments below)

    public class C <T extends Comparable<T>> implements Comparable< C<T> >{...}