I have the class:
class SomeClass<T extends SomeInterface>{
private T[] myArray;
public SomeClass()
{
// I want to initialize myArray in here to a default size of 100
myArray = new T[100]; // this gives an error
}
}
I know I can fix that by requiring a parameter in the constructor as:
class SomeClass<T extends SomeInterface>{
private T[] myArray;
public SomeClass(Class<T> clazz)
{
myArray= (T[]) Array.newInstance(clazz, 100);
}
}
but it makes no scene having to pass the generic parameter twice.
in other words in order to instantiate an object from the class SomeClass I will have to do something like:
SomeClass<SomeOtherClass> obj =
new SomeClass<SomeOtherClass>(SomeOtherClass.class);
I program in c# and Java does not seem to be friendly. I don’t even understand why it is not possible to cast Object[] array to SomeOtherClass[] array. In c# that will be possible…
so my question is how can I avoid having to pass the SomeOtherClass.class parameter in order to be able to construct an array of the generic type in the constructor of the class…
Yes, you would have to pass in the
.classlike that in order to make this work.You could avoid all of this and just use an
ArrayList<T>instead. When you need it in the form of an array you can use:(T[]) myArrayList.toArray()