Suppose I want to have a class for polynomials:
public class Polynomial<T> {
private T[] coefficients;
}
where I need to store the coefficients in an array. I want this array to be as fast as possible, so for most of the cases, I'd like it to be a long[]
. However, I'd also like to support some cases where it is a BigInteger[]
array.
I've been reading about generic arrays in How to create a generic array in Java? and it looks like this case:
public class GenSet<E> {
private E[] a;
public GenSet(Class<E> c, int s) {
// Use Array native method to create array
// of a type only known at run time
@SuppressWarnings("unchecked")
final E[] a = (E[]) Array.newInstance(c, s);
this.a = a;
}
E get(int i) {
return a[i];
}
}
would not work for long
. Maybe I'd have to use Long
, for which I'd have some performance penalties I guess. The unchecked case, on the same answer, is even worse as things are just an Object
.