How to define bound type parameters in Java inner class

811 views Asked by At
public class TowerOfHanoi<E> {
    private class Disk<T extends Comparable<E>> {
    }

    private class Peg<S extends Disk<T extends Comparable<E>>> extends Stack<Disk<T extends Comparable<E>>> {
    }
}

With the above code, I'm getting the following compilation error.

Syntax error on token "extends", , expected

However, if I change the definition of Peg as follows, it works:

private class Peg<T extends Disk<? extends Comparable<E>>> extends Stack<Disk<? extends Comparable<E>>> {
}

I don't want to use a wildcard. Is there a way to change that to a named parameter?

2

There are 2 answers

3
Bohemian On BEST ANSWER

You can't use generics like that. Simply pass the type (not the bound) to the extended type.

This compiles:

public class TowerOfHanoi<E> {
    private class Disk<T extends Comparable<E>> {
    }

    private class Peg<T extends Disk<Comparable<E>>> extends Stack<Disk<Comparable<E>>> {
    }
}
5
tom On

Is there any reason why you can't make E comparable?

public class TowerOfHanoi<E extends Comparable<? super E>>
{
    private class Disk implements Comparable<Disk> { }

    private class Peg extends Stack<Disk> { }
}