Anton
Anton

Reputation: 21

Java Generic class bound to type extending T<E>

I have a generic test class that is generic over the type of a collection (stack in my case) it tests.

Let the name of the generic type be S (for Stack). I have an interface IStack<E> and I want to require S to implement IStack<E>. When I declare my class as class Test<S extends IStack> { ... }, I get a warning:

IStack is a raw type, References ... should be parameterized.

class Test<S<E> extends IStack<E>> leads to a syntax error

Syntax error on token '<', , expected

What's the right way to declare this kind of bound in Java?

Upvotes: 2

Views: 124

Answers (2)

Karol Dowbecki
Karol Dowbecki

Reputation: 44962

class Test<S extends IStack> uses a raw type of IStack, there is no compile-time information of what is inside IStack.

You can do few things, it's entirely up to your design:

  • class Test<S extends IStack<?>> to allow for any element type in IStack
  • class Test<E, S extends IStack<E>> to bind IStack to a specific E element type
  • class Test<S extends IStack<S>> to confuse everyone

Upvotes: 2

I think you need two generic parameters, one for element, another one for stack type, i.e.

class Test<E,S extends IStack<E>>

(or E extends SomeAncestorOfYourElements if needed)

Upvotes: 4

Related Questions