[英]How to have at least two elements of a array with the same length in Java?
[英]my array elements have the same id in Java?
這基本上是一個將兩個稀疏矩陣相乘的程序。 當我想設置為對象創建的數組的元素時,我有一個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) ;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.