user1506919
user1506919

Reputation: 2607

Java Polynomial Multiplication with ArrayList

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.

Upvotes: 1

Views: 5102

Answers (3)

cat916
cat916

Reputation: 1361

Take a look at these codes :

/**
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer.
 */
private transient Object[] elementData;

/**
 * The size of the ArrayList (the number of elements it contains).
 *
 * @serial
 */
private int size;

public ArrayList(int initialCapacity) {
super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
this.elementData = new Object[initialCapacity];
}

public int size() {
   return size;
}

At this time, you have to create an instance by constructor they do not have assign the variable "size" where it contains the number of actual elements. That's reason why you get this exception.

Upvotes: 0

Nishant
Nishant

Reputation: 55866

You may want to check there exist an element at (i+j) before you sum it up with. So do this

int elementAtLoc = 0;
if(array.size() > i+j && array.get(i+j) != null ){
   elementAtLoc = array.get(i+j);
}
array.set(i+j, ((list1.get(i) * list2.get(j))+elementAtLoc));

And there is no need of this:

for (int i=0;i<array.size();i++)
    array.add(i, 0);

Since we are taking care of setting 0 in the second loop itself. It saves you extra work of looping just to add zeros.

Upvotes: 0

arshajii
arshajii

Reputation: 129537

Change your first for loop to:

for (int i = 0 ; i < list1.size() + list2.size() ; i++)
    array.add(0);

As you have it, array.size() is initially 0 so that first for loop is never even entered, so nothing is being added to array. An ArrayList's capacity is not the same thing as its size.

Upvotes: 2

Related Questions