This is what I'm trying to do:
import java.lang.reflect.*;
class exampleOuter <T extends Number>
{
private exampleInner<T>[] elements;
public exampleOuter(Class<T> type, int size)
{
elements = (exampleInner<T>[]) Array.newInstance(type, size);
}
}
I was told that if I wanted to create generic arrays of type T, I should use
elements = (T[]) Array.newInstance(type,size);
So I tried to extend that to my custom class and got a ClassCastException (Ljava.lang.Double; cannot be cast to L*mypackagename*.exampleInner; I'm declaring the class in main like this:
exampleOuter<Double> test = new exampleOuter(Double.class,15);
I can declare the inner class just fine and I can also declare arrays that aren't generic of the innerClass, so I imagine it's something in the constructor of the outerClass. Any ideas?
EDIT: I understand what the problem is. When I create a new instance of the array, I create an array of doubles, not of exampleInner. I think. If that's right, I need to find a way to create an array of exampleInner while passing just Double.class to the function.
EDIT 2: I realize generic arrays are not typesafe, but I have to use them anyway because my teacher demands that we use them.
EDIT 3: I was told that to use generic arrays I had to allocate them that way, and to do so I need reflections, I think. The compiler tells me the class is using unsafe or unchecked operations, but I have to use generic arrays and that's the way I know to do it. If there's a better way I'll change the code.