这基本上是一个将两个稀疏矩阵相乘的程序。当我想要设置为对象创建的数组的元素时,我有一个SpEntry类型的数组(一个具有3个即时变量,int行,列,值和getter和setter方法的类)(m_1和m_2是SpArray类的实例)当我想设置每个数组的元素时,我为每个对象是一个SpEntry [] spArray,其大小为非零元素,我喜欢m_1 [0]和&m_1 [1](m_1数组的元素)具有相同的ID,因此当我设置m_1 [0]的行,行,列时,元素也被复制为m_1 [1]的行,行,列,行。
public class SpArray {
public static int N ; //size of NxN matrix
private SpEntry[] spArray;
public SpArray(int nNZ){
spArray = new SpEntry[nNZ]; //nNZ is the number of Non-Zero elements of the sparse matrix
SpEntry init = new SpEntry(0,0,0);
for (int s=0; s<spArray.length ; s++){
spArray[s]= init ;
}
}
//returns the spArray
public SpEntry[] getSpArray (){
return this.spArray;
}
//returns the spArray elements
public SpEntry getSpArray (int index){
return this.spArray[index];
}
这是SpArray类的一部分,并且在主程序中:
public static void main(String[] args) {
int nnz_1;
int nnz_2;
SpArray m_1;
SpArray m_2;
input = new Scanner (System.in);
System.out.println("Please enter the size of your square sparse matrix: ");
SpArray.N = input.nextInt();
//getting the non zero elements of the 1st sparse matrix & making its sparse array
System.out.println(“请在第一个稀疏矩阵中输入非零元素的数量:”); nnz_1 = input.nextInt();
m_1 = new SpArray (nnz_1);
for(int j_1=0; j_1<nnz_1 ; j_1++){
System.out.println("Enter number "+ (j_1+1) + " non-zero element of the 1st sparse matrix");
System.out.println("row: ");
int r_1 = input.nextInt();
System.out.println("column: ");
int c_1 = input.nextInt();
System.out.println("Value: ");
int v_1 = input.nextInt();
/*
SpEntry e_1 = new SpEntry (r_1, c_1, v_1);
m_1.getSpArray()[j_1].setRow(e_1.getRow());
m_1.getSpArray()[j_1].setCol(e_1.getCol());
m_1.getSpArray()[j_1].setVal(e_1.getVal());
*/
//new versiin revised
SpEntry e_1 = new SpEntry (r_1, c_1, v_1);
m_1.getSpArray(j_1).setRow(e_1.getRow());
m_1.getSpArray(j_1).setCol(e_1.getCol());
m_1.getSpArray(j_1).setVal(e_1.getVal());**
}
当我调试程序时,它表明m_1的数组的元素具有相同的id(和m_2的层相同):
m_1 Value: SpArray (id=21)`enter code here`
spArray SpEntry[2] (id=22)
[0] SpEntry (id=661)
[1] SpEntry (id=661)
您的问题在这里:
public SpArray(int nNZ){
spArray = new SpEntry[nNZ]; //nNZ is the number of Non-Zero elements of the sparse matrix
SpEntry init = new SpEntry(0,0,0); // Problem here
for (int s=0; s<spArray.length ; s++){
spArray[s]= init ;
}
}
您只创建一个对象,然后用同一对象填充整个矩阵。
如果要使对象与众不同,则需要为每个元素创建一个新对象:
public SpArray(int nNZ){
spArray = new SpEntry[nNZ]; //nNZ is the number of Non-Zero elements of the sparse matrix
for (int s=0; s<spArray.length ; s++){
spArray[s]= new SpEntry(0,0,0) ;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句