How to create Generic Array in JAVA
I'd very much appreciate if somebody could provide a pointer on how to do the following.
I've defined a generic interface MyInterface<T> and several classes that implement this interface. I'd like to create an array the members of which can be assigned any object belonging to a class that implements the interface.
I know that an Object array would solve the problem of assigning objects from different classes. However, this is not very clean as I had lose type information and I had have to cast each time I get something from the array.
I've considered java.lang.reflect.Array.newInstance( Class C, int size ) but this requires a single class C and I'd end up with an array which only allows me assignments of C subclass objects.
Ideally, I'd like to declare the array as follows: MyInterface<Type>[] array, for a specific raw type.
Is there a way to do this?
Thanks in advance for your help.
Regards,
Re: How to create Generic Array in JAVA
I have attached the following code snippet (which works) i want to create a 2D generic array with the following method signature
public static <T> T[][] createArray(List<List<T>> list,Class<T> clazz)
Code:
public static <T> T[] createArray(List<T> list,Class<T> clazz){
T[] array = (T[]) Array.newInstance(clazz, list.size());
for(int i = 0; i < array.length; i++){
array[i] = list.get(i);
}
return array;
}
Re: How to create Generic Array in JAVA
arrays and generics do not work together with current versions of Java (for any sufficiently interesting definition of "work together")
You can only define arrays for non-generic types, and do casts in all the accessors.
Re: How to create Generic Array in JAVA
The only way to do it is to use the wildcard HashMap<?, ?>[] x=new HashMap<?, ?>[3]
The reason behind this particular design was to maintain compatibility with existing code. This is directly related to generics. Generic types for which arrays cannot be created are said to be non-reifiable. The meaning of reify according to the dictionary is to treat something abstract as if it was concrete. The meaning makes it a bit easier to understand