0

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("");
    }
}
Lajos Arpad
  • 45,912
  • 26
  • 82
  • 148
  • Can you rephrase the question for better understanding? Is it java? – manikanta nvsr Apr 05 '20 at 16:34
  • Yes, it is in Java. If I, for example, have an array Integer[] a = {2, 3, 4} I need my program to print this: 2 3 4 4 9 16 16 81 256 (every next row is elements of the previous one multiplied by themselves). Sorry for bad English. –  Apr 05 '20 at 16:42

2 Answers2

0

This is your problem:

E[][] matrica = (E[][]) new Object[n][n];

Do this (cls is of type Class<E>):

@SuppressWarnings("unchecked")
E[][] matrica = (E[][]) Array.newInstance(cls, n, n);

Reference

Šimon Kocúrek
  • 1,218
  • 1
  • 8
  • 17
0

According to this link, Java generics are not designed in a way to perform arithmetic operations. I hope it helps you regarding generic methods and arithmetic operations: Using a generic class to perform basic arithmetic operations

  • 1
    "E" because it's a generic method. Later I need to make an array of integers, doubles, and floats to prove that it can work with all of them. –  Apr 05 '20 at 16:54
  • According to this link, Java generics are not designed in a way to perform arithmetic operations. I hope it helps you regarding generic methods and arithmetic operations: https://stackoverflow.com/questions/14046209/using-a-generic-class-to-perform-basic-arithmetic-operations – manikanta nvsr Apr 05 '20 at 17:00
  • That is exactly my problem, it tells me that I can't use * on E. Thank you very much! –  Apr 05 '20 at 17:04
  • @Neru Welcome!! – manikanta nvsr Apr 05 '20 at 17:05