I need to make a generic function that takes an array of numbers (integers, doubles or whatever else), and then make a 2D array in which the first row is that array and every next row is the previous one squared. What I made gives me a
java.lang.object cannot be cast to java.lang.number
even though I put E extends Number
. I tried the same function using just int and it does what I need it to do.
Where did I make a mistake? Am I using the "E extends Number" wrong?
public static<E> void napraviMatricu(E[] niz) {
int n = niz.length;
E[][] matrica = (E[][]) new Object[n][n];
for(int i = 0; i < matrica[0].length; i++)
matrica[0][i] = niz[i];
for(int i = 1; i < matrica.length; i++)
for(int j = 0; j < matrica[i].length; j++)
matrica[i][j] = matrica[i-1][j] * matrica[i-1][j];
for(int i = 0; i < matrica.length; i++) {
for(int j = 0; j < matrica[i]. length; j++)
System.out.print(matrica[i][j] + " ");
System.out.println("");
}
}