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?
Java’s handling of generics is in pretty rough shape but you can accomplish something close to what you want if you are prepared to make small adjustments. Please see:
And a use case:
This is just a rough example although I am sure you could accomplish something similar without having to use this approach.