aspose file tools*
The moose likes Beginning Java and the fly likes generic and arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "generic and arrays" Watch "generic and arrays" New topic
Author

generic and arrays

Tian Zhang
Greenhorn

Joined: Mar 23, 2005
Posts: 26
hello!

could someone suggest what a solution for the following code would be?



at the moment i have to up cast everything to Object as the above is illegal:


this creates a problem as if i wanted to iterate through the array using the new syntax:



becomes illegal.

thanks,
tian
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

See if this helps.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Tian Zhang
Greenhorn

Joined: Mar 23, 2005
Posts: 26
hello,

thanks for the link, though unfortunatly i didnt find it that useful i'm sure it will be useful to others!

i've ended up with some ugly casting as googling: generic arrays by luck landed me on page that comfirmed what i had suspected in the first post.

thanks,
tian
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
One option is to not use arrays at all, and use List<MyType> instead. Another, if you really really need arrays of the appropriate type, is to have your instance keep a reference to the Class it's associated with (require it in the constructor or factory method). Then use java.lang.reflect.Array.newInstance(clss, size) to create the appropriate array.


"I'm not back." - Bill Harding, Twister
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Tian Zhang:
hello!

could someone suggest what a solution for the following code would be?



at the moment i have to up cast everything to Object as the above is illegal:


this creates a problem as if i wanted to iterate through the array using the new syntax:



becomes illegal.

thanks,
tian


You have found (one of many limitations) a limitation of generics. You'll find evidence of your best case scenario in places such as the source to java.util.ArrayList or net.tmorris.adt.set.MutableSet, which amounts to a compile-time warning (or alternatively, something other than an array without O(1) seek).

Welcome to Java


Tony Morris
Java Q&A (FAQ, Trivia)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: generic and arrays