-
April 9th, 2005, 06:00 AM
#1
generic array creation
hi,
i've been playing around with JDK1.5 generics a little bit and at the very first try to create a "GenericStack" i've run into this problem that it's impossible to create arrays of generics in my generic stack. i've tried to implement the stack with a simple array of the generic object.
what's the workaround, proper approach?
if you find it useful - rate it!
/******\
|__|-o | |
\******/
-
April 9th, 2005, 08:33 AM
#2
Re: generic array creation
If you read up on how generics are implemented in Java 5.0, you'll see that there are restrictions on the component type of arrays:
"The component type of an array object may not be a type variable or a parameterized type, unless it is an (unbounded) wildcard type.You can declare array types whose element type is a type variable or a parameterized type, but not array objects...
...attempting to create an array object whose element type is a type variable
causes a compile-time error:
Code:
<T> T[] makeArray(T t) { return new T[100]; // error
}
Since type variables don’t exist at run time, there is no way to determine what the actual array type would be. The way to work around these kinds of limitations is to use class literals as run time type tokens..." - Java Generics Tutorial - section 7.3.
Section 8 of the Java Generics Tutorial covers using class literals as run time type tokens.
However, it seems to me a mistake to try and base a stack on an array in any case, because they are fundamentally incompatible - a stack is a variable length container whereas an array is fixed length. Wouldn't it be better (and easier) to base it on a generic collection class such as ArrayList<T> ? Just don't make the mistake they made in java.util.Stack of extending the collection class (Vector).
Simplicity is the ultimate sophistication...
Leonardo Da Vinci
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
-
April 9th, 2005, 11:14 AM
#3
Re: generic array creation
According to Neal Gafter(the person who wrote the Java compiler and some of the java libraries) in his blog, the proper way is to preserve the type token after erasure by using reflections. Bruce Eckel, in his old weblogs, also investigated type erasure (which prompted Gafter to make a reply on his blog), which you can read about:
http://mindview.net/WebLog (titled Puzzling through Erasure)
Neal Gafter's blog: http://gafter.blogspot.com/2004/09/p...re-answer.html
Hungarian notation, reinterpreted? http://www.joelonsoftware.com/articles/Wrong.html
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|