0

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.

Rafaelo
  • 33
  • 1
  • 15
  • 2
    Generics cannot be used asprimitives (except wrappers). That's it. – dan1st Sep 29 '21 at 19:26
  • " 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." biginteger and long don't have much in common. Are you really sure you want to have both in a same array? That will have plenty of perf penalties. – eis Sep 29 '21 at 19:27

0 Answers0