英文:
How to make a 2D array where every next row is the previous row squared in Java?
问题
public static<E extends Number> 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("");
}
}
英文:
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("");
}
}
答案1
得分: 0
这是您的问题:
E[][] matrica = (E[][]) new Object[n][n];
请进行以下操作(cls
的类型为 Class<E>
):
@SuppressWarnings("unchecked")
E[][] matrica = (E[][]) Array.newInstance(cls, n, n);
英文:
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);
答案2
得分: 0
根据此链接,Java 泛型并不是设计用来执行算术操作的。希望对您有关于泛型方法和算术操作的问题有所帮助:
链接地址
英文:
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
专注分享java语言的经验与见解,让所有开发者获益!
评论