prunes4u
prunes4u

Reputation: 43

Creating an array of generic stacks

Stack<E>[] stacks = {new Stack<Bed>(), new Stack<Bookshelves>(), 
                     new Stack<Chair>(), new Stack<Desk>(), new Stack<Table>()};

For class I had to make my own Stack class that takes in whatever object I specify. As per specification, I have to put all the Stacks into an array.

But, when I try to create an Array of Stacks, I get a "cannot find symbol: class E" error.

What can I do to create an array of generic stacks?

Upvotes: 1

Views: 217

Answers (1)

Paul
Paul

Reputation: 1088

Generic type declarations such as <E> only work when you are defining a class, like

public class Stack<E>{
 // etc.
} 

To create an array of Stacks like you are doing, you could either use the wildcard generic:

Stack<?>[] stacks = {new Stack<Bed>(), new Stack<Bookshelves>(), new Stack<Chair>(), new Stack<Desk>(), new Stack<Table>()};

Or if all your objects inside the stacks share a common inheritance, you could narrow down the wildcard with something like

Stack<? extends Furniture>[] stacks = {new Stack<Bed>(), new Stack<Bookshelves>(), new Stack<Chair>(), new Stack<Desk>(), new Stack<Table>()};

Upvotes: 6

Related Questions