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.
[java] Elegant way to create new generic type, or array of generic types
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.
[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.
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement