• Post Reply Bookmark Topic Watch Topic
  • New Topic

creating an array of generic type  RSS feed

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37513
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yesterday I spent about an hour trying to find out how to create an array of a generic type. I found responses saying it's impossible along with some helpful advice. I thought I saw it posted in this forum once, but couldn't find it yesterday. So logically, I should start a thread here so that next time I look for this piece of code, it is someplace I will think to look!



I also found a site that shows how to find the component type class for the generic based on an array or collection type.
 
Ganesh Gowtham
Ranch Hand
Posts: 225
IBM DB2 Eclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne

May i know your requirement bit clearer ? with input and output ,So that i can help you .

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ganesh, Jeanne did not post a question - she posted a useful piece of code for herself and others to find.

Unfortunately, using a Class object is the only way as Jeanne has shown.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main reason why you can't create arrays of generic types is because of the combination of type erasure and the way arrays work in Java - arrays are covariant, but this is implemented in Java with a check at runtime. The check doesn't work for generic types, because information necessary for the check is lost due to type erasure.

Here's a blog post I wrote about it: http://www.bloggingaboutjava.org/2006/01/java-generics-quirks/
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looking at the code in the first post, I think it might work a little better if the lines are reversed.

Angelika Langer's generics FAQ is also an excellent resource for this sort of thing.

The notion of "array of generic type" can be interpreted several different ways, some of which are possible, and some which aren't. Compare

Can I create an array whose component type is a type parameter?


with

Can I create an array whose component type is a concrete parameterized type?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!