Aaron
Aaron

Reputation: 1

Why this class cannot be compiled?

public class Foo<E> implements Comparable<E> {
    E a ;
    public Foo ( E a ) {
        this.a =a;
    }
    public int compareTo ( E b ) {
        return a.compareTo ( b ) ;
    }
}

I do not know why these code cannot be compiled.

Upvotes: 0

Views: 37

Answers (1)

Niyoko
Niyoko

Reputation: 7662

Generic parameter E does not guaranteed to have compareTo method, so it will fail to compile.

If you add some constraint so E is guaranteed to have compareTo method, then it will compile.

public class Foo<E extends Comparable<? super E>>

Upvotes: 1

Related Questions