1
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?

2
  • 2
    You cannot create an array of generics. But what would you want to do with it if you could? Commented Mar 25, 2012 at 22:15
  • 2
    You're almost certainly better off creating a List of Stacks. (Although for your particular case, I frankly think you shouldn't create an array or list at all, but should keep the lists of the different types as explicit, separate variables.) Commented Mar 25, 2012 at 22:32

1 Answer 1

6

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>()}; 
Sign up to request clarification or add additional context in comments.

1 Comment

Stack<?>[] works, but Stack<? extends Furniture>[] doesn't because you cannot create generic arrays, at least not with that nice short syntax :/

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.