views:

237

answers:

6
+1  Q: 

array of stacks

Is it possible to create an array of stacks without having to cast the stacks as they come out? Eclipse gives me a warning about not being able to make a generic array of Stack when I do something like this:

Stack<Card>[] cards = new Stack<Card>[52];
A: 

Well, the array does not need to be a generic because he is always defined as this. Why do you think you have to cast? I think that eclipse is somewhat confused here.

Norbert Hartl
eclipse is not confused: "...It is a compile-time error if the element type is not a reifiable type..." see http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.3
Carlos Heuberger
+1  A: 

Why do you use arrays anyway ?

It is a low level programming structure.

Using List or Set instead (eg org.apache.commons.collections.list.LazyList) if you don't want to bother with innitialization.

Or at least

Arrays.asList(new Stack[52]) to wrap an array into a list.

I couldnt reproduce jour error anywany .. :( perchaps it's because a different warning/errorlevel set.

lbownik
Using an array I can limit the number of stacks within it, as the list is an interface, all implementations of the list are not exactly what I need it for.
see org.apache.commons.collections.list.FixedSizeList
KitsuneYMG
+2  A: 

You can do the following, though this gives you a compiler "unchecked" warning.

Stack<Card>[] cards = (Stack<Card>[]) new Stack[52];
Peter Lawrey
Wow, thanks for remembering me that I hate generics :) To be honest making code ugly only that your stupid IDE does not complain is not a good reason to do.
Norbert Hartl
Thanks for the answer, but I would like to not have to cast them as they come out. Have to follow a tight spec that doesn't allow them to be casted out.
@Nobert Hartl: it's not the IDE, it's the Java Language Specification!
Carlos Heuberger
A: 

It's to do with type erasure. Basically the generic types only exist at compile time and have no presence at run time

Have at look at this forum post for a better explanation.

Cogsy
+2  A: 

Joshua Bloch does an excellent job of describing this problem in Effective Java, Second Edition. Check out the relevant section on Google Book Search.

The advice he offers is to prefer lists to arrays. Your code might then look something like:

List<Stack<Card>> cards = new ArrayList<Stack<Card>>();
harto
A: 
Stack<Card>[] decks = new Stack[9];       // Declare
Card c = decks[5].pop();                  // This compiles - java 'knows' the type
Integer i = decks[4].pop();               // This will not compile