Creating a Generic array

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
 
G

googmeister

How do I allocate an array of arbitrary type T?

You can't in Java.
in unchecked version my code was simply:
stack = new Object[ size ];

You can continue to do this, but in pop(),
cast the result to T before returning it. This
will result in a warning that you can ignore.
You can also use the (T[]) new Object[size]
trick. It works because of type erasure. Note
that ArrayList doesn't compile cleanly either.

As far as I know, you can't get a generic array
implementation of a stack to compile without
a warning. I'm not sure whether this is because
of the way generics are implemented in Java
or in the way arrays are implemented in Java,
but either way, I consider it a substantial language
defect. Do others agree?
 
R

Roedy Green

You can continue to do this, but in pop(),
cast the result to T before returning it. This
will result in a warning that you can ignore.
You can also use the (T[]) new Object[size]
trick. It works because of type erasure. Note
that ArrayList doesn't compile cleanly either.

So the cast really does not do anything. the internal array REALLY is
an array of Objects not an array of T. I could not export the array
itself outside the generic class.

Surely I should be able to construct an object of generic type T or
is the problem just with arrays of T?

Generics make me queasy. They smell of eau de kludge. In is an
assembler coder's creation to allow typesafe containers.

Instead of generics, I would have wished for more ability to pass
classes around as objects and do things to them you now have to resort
to reflection for.


--
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
 
S

Stefan Schulz

As far as I know, you can't get a generic array
implementation of a stack to compile without
a warning. I'm not sure whether this is because
of the way generics are implemented in Java
or in the way arrays are implemented in Java,
but either way, I consider it a substantial language
defect. Do others agree?

I for one agree. Code that needs to ignore warnings to work is never lean.
Okay, Arrays where always a little dirty (ArrayStoreException anyone?),
but still, if we already have type-unsafe arrays (Object [] x = new
String []), then make the whole step and allow generic arrays.
 
A

Andrea Desole

Roedy said:
Surely I should be able to construct an object of generic type T or
is the problem just with arrays of T?

after the discussion about tokens and factories in another thread, I
just tried to do that: you can't. And I can't see why
Generics make me queasy. They smell of eau de kludge. In is an
assembler coder's creation to allow typesafe containers.

indeed, generics are not really generic
 
R

Roedy Green

after the discussion about tokens and factories in another thread, I
just tried to do that: you can't. And I can't see why

I have been thinking about the various rumours I have heard and I put
together my theory that would explain why you can't construct objects
of type T or arrays of type T. It is a side effect of the el-cheapo
way Generics were implemented.

Generics are just a glorified compile time type checking on the same
old code.

It also explains why generics force you to allocate the precise same
type as the variable declaration for every use of that variable.

I posted it in a thread called something like "getting my head around
generics"

When I am clear on just what is so, I will write an essay explaining
how this all works.

I find so often understanding AN implementation model suddenly makes
all the peculiar restrictions make sense. It easy then to remember
how it works and all the expected peculiar behaviour.

It does not matter if the model is 100% accurate. It just has to be
close enough to predict high level behaviour.

To sort this out definitively, I should go looking for a disassembler
than works on Java 1.5.



--
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
 
L

Lasse Reichstein Nielsen

Roedy Green said:
Surely I should be able to construct an object of generic type T or
is the problem just with arrays of T?

If all you have is the type variable, then no, you can't create an
object from that. You don't know what type it is, so you don't know
what constructors are available. That's why you can't write just
new T()
.... nobody knows whether the type T has a no-arg constructor.
Generics make me queasy. They smell of eau de kludge. In is an
assembler coder's creation to allow typesafe containers.

It's not that bad. Other languages have entirely static type systems
too (e.g., SML or Haskell). It's just that combining generic types
with type inheritance makes everything a lot more complicated :).
In non-OO languages, if you have something of type T, you don't
start worrying about *which* (sub)type of T it is.
Instead of generics, I would have wished for more ability to pass
classes around as objects and do things to them you now have to resort
to reflection for.

You want first class types? Or what kind of "things" do you want to
do with them?

You could do simple wrapper classes around Class that hid the
reflection, but that might be too hackish too? Might as well use
Javascript, or Smalltalk, then. Java is a statically typed language,
with all the restrictions (and safeguards) entailed by that.

/L
 
C

ChrisWSU

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

the casting of an array makes sense, a java.lang.reflect.Array is
generated via Array.newInstance( ... ) which is a Object, you simply
have to cast it.

i think this will work
stack = (T[])Array.newInstance(stack.getClass(),size);

it comes up with a warning but it makes sense
 
R

Roedy Green

You want first class types? Or what kind of "things" do you want to
do with them?

write a factory that can create an a variety of objects subclasses of
the some base class without having to put explicit new code in there
for every possible type.

Write methods that can return an array of type without having to pass
in an empty array of T for it to fill.

No need for reflection when some sort of interface makes a guarantee
about what methods and constructors and statics will be available.

Treating statics more like Class instance methods. When classes
inherit statics, you = be able to dynamically select the correct
static method given the base class name at compile time and the
subclass name at runtime.


--
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
 
T

Tim Tyler

Roedy Green said:
On Wed, 06 Jul 2005 13:48:05 +0200, Lasse Reichstein Nielsen


write a factory that can create an a variety of objects subclasses of
the some base class without having to put explicit new code in there
for every possible type.

Write methods that can return an array of type without having to pass
in an empty array of T for it to fill.

No need for reflection when some sort of interface makes a guarantee
about what methods and constructors and statics will be available.

You sound like you are after a dynamic language. To do most of those in
Java, it's a case of getting up to your elbows in the reflection API.
 
R

Remon van Vliet

To sort this out definitively, I should go looking for a disassembler
than works on Java 1.5.

That wont help you much, Generics are used for compile-time type safety, and
as such there will be no changes visible in the generated bytecode.

Remon
 
R

Roedy Green

That wont help you much, Generics are used for compile-time type safety, and
as such there will be no changes visible in the generated bytecode.

Right. However the decompiler instantly made enums clear.

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,610
Members
45,254
Latest member
Top Crypto TwitterChannel

Latest Threads

Top