Java Polynomial Multiplication with ArrayList
Posted
by
user1506919
on Stack Overflow
See other posts from Stack Overflow
or by user1506919
Published on 2012-09-09T03:06:26Z
Indexed on
2012/09/09
3:38 UTC
Read the original article
Hit count: 284
I am having a problem with one of my methods in my program. The method is designed to take 2 arraylists and the perform multiplication between the two like a polynomial.
For example, if I was to say list1={3,2,1}
and list2={5,6,7}
; I am trying to get a return value of 15,28,38,20,7
. However, all I can get is an error message that says:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
.
I have provided the method below:
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;
}
Any help with solving this problem is greatly appreciated.
© Stack Overflow or respective owner