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

Started by
5 comments, last by Danny02 12 years, 11 months ago
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.
--------------------------------------Not All Martyrs See Divinity, But At Least You Tried
Advertisement
Which language?
[edit]sorry i thought this was in the general programming sectionunsure.gif
Java, sorry i figured I could omit that since this the Java forum. Specifically Java SE 6.
--------------------------------------Not All Martyrs See Divinity, But At Least You Tried
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.

Omae Wa Mou Shindeiru

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.

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.
--------------------------------------Not All Martyrs See Divinity, But At Least You Tried
just use a Collection

This topic is closed to new replies.

Advertisement