R
Roedy Green
I was trying to make my little stack class type safe. Internally it
has a simple array to hold the stack elements.
How do I allocate an array of arbitrary type T?
public class Stack<T> {
/**
* array to hold the stack elements.
* The top of the stack is stored in the
* highest index.
*/
private T[] stack;
private int size;
/**
* Constructor for a pushdown stack.
*
* @param size
* maximum stack depth.
* Cannot grow beyond this depth. Allocates RAM
* for this deep.
*/
public Stack( int size )
{
// in unchecked version my code was simply:
// stack = new Object[ size ];
// I can't say
// stack = new T[size];
// gets a syntax error
// "cannot create a generic array of T."
// Here is what ArrayList does,
// stack = (T[]) new Object[size];
// but that makes no sense.
// It generates a warning and you can't do such a cast.
// You can't cast an Object[] to a String[] even
// even if all the elements are strings
// Should that not generate a cast exception?
--
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm
Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes
has a simple array to hold the stack elements.
How do I allocate an array of arbitrary type T?
public class Stack<T> {
/**
* array to hold the stack elements.
* The top of the stack is stored in the
* highest index.
*/
private T[] stack;
private int size;
/**
* Constructor for a pushdown stack.
*
* @param size
* maximum stack depth.
* Cannot grow beyond this depth. Allocates RAM
* for this deep.
*/
public Stack( int size )
{
// in unchecked version my code was simply:
// stack = new Object[ size ];
// I can't say
// stack = new T[size];
// gets a syntax error
// "cannot create a generic array of T."
// Here is what ArrayList does,
// stack = (T[]) new Object[size];
// but that makes no sense.
// It generates a warning and you can't do such a cast.
// You can't cast an Object[] to a String[] even
// even if all the elements are strings
// Should that not generate a cast exception?
--
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm
Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes