Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / July 2005

Tip: Looking for answers? Try searching our database.

Creating a Generic array

Thread view: 
Roedy Green - 06 Jul 2005 00:23 GMT
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?
 

Signature

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

googmeister@gmail.com - 06 Jul 2005 03:24 GMT
> 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?
Roedy Green - 06 Jul 2005 07:27 GMT
>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.

Signature

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

Andrea Desole - 06 Jul 2005 09:53 GMT
> 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
Roedy Green - 06 Jul 2005 10:55 GMT
>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.

Signature

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

Stefan Schulz - 06 Jul 2005 11:05 GMT
>  
> To sort this out definitively, I should go looking for a disassembler
> than works on Java 1.5.

http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html

This might help you more in way less time

Signature

You can't run away forever,
But there's nothing wrong with getting a good head start.
          --- Jim Steinman, "Rock and Roll Dreams Come Through"
         

Remon van Vliet - 14 Jul 2005 13:09 GMT
> 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
Roedy Green - 14 Jul 2005 22:05 GMT
>> 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.

Right. However the decompiler instantly made enums clear.

Signature

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

Lasse Reichstein Nielsen - 06 Jul 2005 12:46 GMT
> 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
Signature

Lasse Reichstein Nielsen  -  lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
 'Faith without judgement merely degrades the spirit divine.'

Roedy Green - 06 Jul 2005 19:26 GMT
>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.

Signature

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

Tim Tyler - 12 Jul 2005 23:23 GMT
Roedy Green <look-on@mindprod.com.invalid> wrote or quoted:

> >You want first class types? Or what kind of "things" do you want to
> >do with them?
[quoted text clipped - 8 lines]
> 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.
Signature

__________
|im |yler  http://timtyler.org/  tim@tt1lock.org  Remove lock to reply.

Stefan Schulz - 06 Jul 2005 09:39 GMT
On Tue, 05 Jul 2005 19:24:39 -0700, googmeister wrote:

> As far as I know, you can't get a generic array
> implementation of a stack to compile without
[quoted text clipped - 3 lines]
> 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.

Signature

You can't run away forever,
But there's nothing wrong with getting a good head start.
          --- Jim Steinman, "Rock and Roll Dreams Come Through"
         

ChrisWSU - 06 Jul 2005 17:56 GMT
>    // Here is what ArrayList does,
>    // stack = (T[]) new Object[size];
[quoted text clipped - 3 lines]
>    // 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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.