我正在尝试在Java中实现"添加"两个数组的元素.我有两个包含整数的数组,我想添加它们.我不想使用不可变变量.我更喜欢这样做:a.plus(b); 问题是当我添加2个不同长度的数组时.它尝试将b的元素添加到a,但如果b的长度更长,则会标记错误"ArrayIndexOutOfBoundsException".我能理解为什么会这样.但我怎么能解决这个问题呢?我怎样才能扩展阵列?:/
public void plus(int[] b)
{
int maxlength = Math.max( this.length, b.length );
if (maxlength==a.length)
{
for (int i = 0; i <= maxlength; i++)
{
a[i] = a[i] + b[i]; //ArrayIndexOutOfBoundsException error
}
}
}
Run Code Online (Sandbox Code Playgroud)
i <= maxlength用它代替i < maxlength.
您的数组索引从零开始,而不是从一开始.因此,数组的长度比数组的结束索引小1.当你使用<=时,你试图在数组中的最后一个元素之后去一个元素,因此异常.
你还要检查数组b的长度.如果数组b的长度小于a,则最终将面临相同的异常.
int maxlength = Math.min( this.length, b.length ); 更合适.
或者如果您不想在添加时错过任何一个数组中的任何元素,ArrayList就是您的最佳选择.ArrayList是您正在寻找的自扩展阵列.这是你如何做到的 -
// First ArrayList
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
// Second ArrayList
ArrayList<Integer> b = new ArrayList<Integer>();
b.add(1);
b.add(2);
b.add(3);
b.add(4);
int maxlength = Math.max(a.size(), b.size());
// Add the elements and put them in the first ArrayList in the corresponding
// position
for (int i = 0; i < maxlength; i++) {
if (i < a.size()) {
if (i < b.size()) {
int j = a.get(i);
a.set(i, j + b.get(i));
}
} else {
a.add(i, b.get(i));
}
}
for (int j : a) {
System.out.println(j);
}
Run Code Online (Sandbox Code Playgroud)