Jump to content
  • Advertisement
Sign in to follow this  
godsenddeath

[java] Elegant way to create new generic type, or array of generic types

This topic is 2778 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm wondering if there's an non-ugly way to create a new instance of a generic, or an array of generic type.

Everywhere I look says either cast from Object, or suppress the warning. Are either of these methods appropriate in a professional situation, like an interview or in production code? They seem really hackish to me.

Share this post


Link to post
Share on other sites
Advertisement
What do you need to cast?
[source lang="java"]List<Foo> var=new ArrayList<Foo>(25);
var.add(new Foo());[/source]
Such basic usage doen't seem hackish or ugly to me.

Share this post


Link to post
Share on other sites
The Java standard library can't do this, neither can you. It is technically impossible to do this, because generics are type-erased at compile time and there is no reflection support for instantiating an array of a given type. Because arrays are covariant, they behave differently depending on which runtime type is used to instantiate them.

In an interview or production code, use a container if you can. If you must use an array, feel free to mention the caveats (in the comments or to the interviewer). Design classes with invariants such that the code prevents covariant array related bugs.

Share this post


Link to post
Share on other sites

What do you need to cast?
[source lang="java"]List<Foo> var=new ArrayList<Foo>(25);
var.add(new Foo());[/source]
Such basic usage doen't seem hackish or ugly to me.


Not exactly, something more like:

T data = (T[])new Object[size];


The Java standard library can't do this, neither can you. It is technically impossible to do this, because generics are type-erased at compile time and there is no reflection support for instantiating an array of a given type. Because arrays are covariant, they behave differently depending on which runtime type is used to instantiate them.

In an interview or production code, use a container if you can. If you must use an array, feel free to mention the caveats (in the comments or to the interviewer). Design classes with invariants such that the code prevents covariant array related bugs.



Thanks for the advice, I'll keep it in mind.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!