I have a class FirstClass<O> and a class SecondClass<O>, and I want to make an O[] in SecondClass<O> inside a routine which is called from FirstClass<O>, where O is a generic class parameter. I fail to find how to do this.
I need an O[] specifically (and not ArrayList<O> or similar) because I need to get elements from it very often inside the body of a loop, and it matters for the execution time of my algorithm.
So I would want something along these lines.
public class FirstClass<O> {
void someRoutine(n and other params) {
//Do some stuff
SecondClass<O> = new SecondClass(n, possibly_other_params);
//Do some stuff
}
}
and
public class SecondClass<O> {
O[] myArray;
SecondClass<O>(int n, possibly_other_params) {
//Here the constructor that creates an O[n]
}
}
Some methods I found on the web, but do not work for my case:
- Use
O[] array = (O[]) new Object[n];but that doesn't compile. - Use
Object[] array = new Object[n];and do an (O) cast every time I request something from the array, but this is way too slow - Use
Array.newInstance(Class<O> type, int n);, withO o;andtype=o.classbut it complains thattypeis now of typeClass<CAP#1>instead of typeClass<O>, whatever CAP#1 means...
How should I do this properly in Java, with optimal execution speed in mind?
ArrayList, sheesh.a[i]=a[j]to obtain some permutation is quite a bit cheaper than doinglist.set(i,list.get(j))all the time. Putting a fixed array type makes it indeed faster, but then I need to make copy-paste the code for each of the 25 possible types O can be, and that's not really good style. :/ Well, if it's not possible then it's not possible of course. Thanks for the input anyway.