这基本上是一个将两个稀疏矩阵相乘的程序。我有一个SpEntry类型的数组(一个有3个即时变量的类,int行,列,值和& getter& setter方法),当我想设置为我的对象创建的数组的元素时(m_1& m_2是实例)类SpArray& for每个都有一个大小为非零元素的SpEntry [] spArray) 当我想设置每个阵列的元素时,我喜欢m_1 [0],& m_1 [1](m_1数组的元素)具有相同的id,因此当我设置m_1 [0]的row,col,val时,元素被复制为m_1 [1]的row,col,val as井
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的相同strory):
m_1 Value: SpArray (id=21)`enter code here`
spArray SpEntry[2] (id=22)
[0] SpEntry (id=661)
[1] SpEntry (id=661)
答案 0 :(得分:1)
你的问题在这里:
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 ;
}
}
您只创建一个对象,并使用相同的对象填充整个matrx。
如果希望对象不同,则需要为每个元素创建一个新对象:
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) ;
}
}