我在我的程序中遇到了一個問題。該方法設計爲採用2個陣列列表,並在兩者之間執行乘法運算,如多項式。使用ArrayList進行Java多項式乘法運算
例如,如果我要說list1={3,2,1}
和list2={5,6,7}
;我試圖獲得15,28,38,20,7
的返回值。然而,我所能得到的只是一個錯誤信息:
線程「main」的異常java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
。
我提供以下方法:
private static ArrayList<Integer> multiply(ArrayList<Integer> list1,ArrayList<Integer> list2) {
ArrayList<Integer> array =new ArrayList<Integer>(list1.size()+list2.size());
for (int i=0;i<array.size();i++)
array.add(i, 0);
for (int i = 0; i < list1.size(); i++)
for (int j = 0; j < list2.size(); j++)
array.set(i+j, ((list1.get(i) * list2.get(j))+array.get(i+j)));
return array;
}
有解決這個問題的任何幫助是極大的讚賞。
是的,當我調用其他方法(如加減法)時,list1和list2都可以正常工作 – user1506919