尝试清空数组时超出界限的数组在循环中列出



我有一个函数来计算每个二维矩阵行与矩阵中第一行的余弦相似性。然后,每行的余弦相似性将被添加到称为激活的数组列表中。

这是代码:

 List <Double> probeVectorList = new ArrayList <Double>();
 Double[] probeVectorArr = new Double[countMatrix2[0].length];
 List <Double> contextVectorList = new ArrayList <Double>();
 Double[] contextVectorArr = new Double[countMatrix2[0].length];
 List <Double> activation = new ArrayList <Double>();
 //display matrix
 for (int i = 0; i < countMatrix2.length; i++) {
    System.out.print(arrKeyWords[i]+"   "); //print keywords
    for (int j = 0; j < countMatrix2[0].length; j++) { 
         if (i==0)
         {
             probeVectorList.add(RoundTo2Decimals(contextVector[i][j])); //set the first row as probe vector
             probeVectorArr = probeVectorList.toArray(new Double[0]);
         }
            System.out.print(RoundTo2Decimals(contextVector[i][j])+", "); //print the entire matrix with rounded decimals
            //compute activation
           contextVectorList.add(RoundTo2Decimals(contextVector[i][j])); //here, in every iteration, the rows will be added into the list
           contextVectorArr = contextVectorList.toArray(new Double[0]); //convert list to array
           activation.add(cosineSimilarity(probeVectorArr, contextVectorArr)); //compute cosine similarity between the first row(static) and the subsequent row (cosineSimilarity function will take in 2 vector as input)
             } 
           //array out of bounds exception appears when attempting to calculate cosine similarity whenever I empty the array/list to make way for new rows 
          Arrays.fill(contextVectorArr, null); //empty array to make way for new rows
          contextVectorList.clear(); //empty list to make way for new rows
          System.out.println(" "); 
       }

正如评论所建议的那样,每当我尝试清空列表以便为下一行让路时,它都会在行activation.add(cosineSimilarity(probeVectorArr, contextVectorArr));上显示Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1。如果我不清空它,它将正常工作,这将导致每一行都被添加到列表中。(矩阵包含每行相同的列数)...

有人可以帮忙吗?谢谢!

每次迭代都以空列表开始,您的contextVectorList,因此派生的contextVectorArr,只包含一个由该行添加的元素

contextVectorList.add(RoundTo2Decimals(contextVector[i][j]));

因此,指数1确实超出了范围。

最新更新