我的程序中有一个方法有问题。该方法被设计为采用2个arraylists并且两者之间的执行乘法类似于多项式。
例如,如果我要说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 :(得分:2)
将您的第一个for循环更改为:
for (int i = 0 ; i < list1.size() + list2.size() ; i++)
array.add(0);
如果你拥有它,array.size()
最初是0
,因此永远不会输入第一个for循环,因此没有任何内容添加到array
。 ArrayList
的容量与其大小不同。
答案 1 :(得分: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
。它为您节省了额外的循环工作,只是为了添加零。
答案 2 :(得分: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;
}
此时,您必须通过构造函数创建一个实例,它们没有为变量“size”分配实际元素的数量。这就是你得到这个例外的原因。