2012-09-09 103 views
1

我在我的程序中遇到了一個問題。該方法設計爲採用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; 

} 

有解決這個問題的任何幫助是極大的讚賞。

+0

是的,當我調用其他方法(如加減法)時,list1和list2都可以正常工作 – user1506919

回答

2

更改您的第一個for循環:

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

當你擁有它,array.size()最初0,使第一個for循環中甚至從來沒有進入,所以沒有被添加到arrayArrayList的容量與其尺寸不同。

+0

謝謝,這解決了我的問題 – user1506919

+0

很高興能幫到你。 – arshajii

0

在總結之前,您可能需要檢查是否存在(i+j)處的元素。所以做這個

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)); 

而且也沒有必要這樣:

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

由於我們採取在第二循環中本身設置0的照顧。它可以爲您節省額外的循環工作只需添加零點

0

在這些代碼看看:

/** 
* 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; 
} 

在這個時候,你必須創建通過構造一個實例他們沒有分配變量「大小」,其中包含實際的元素個數。這就是你得到這個例外的原因。