Java 因Apache common.lang ArrayUtils.remove导致IndexOutOfBoundsException
代码: 错误:Java 因Apache common.lang ArrayUtils.remove导致IndexOutOfBoundsException,java,arrays,apache,indexoutofboundsexception,Java,Arrays,Apache,Indexoutofboundsexception,代码: 错误: import org.apache.commons.lang.ArrayUtils; int[] arr = new int[] { 2, 3, 4, 5, 6, 7, 8 }; int index = 0; for (int whit : arr) { if (whit % 2 == 0) arr = ArrayUtils.remove(arr, index);
import org.apache.commons.lang.ArrayUtils;
int[] arr = new int[] { 2, 3, 4, 5, 6, 7, 8 };
int index = 0;
for (int whit : arr) {
if (whit % 2 == 0)
arr = ArrayUtils.remove(arr, index);
index++;
}
Java版本:1.7
有人能帮我安全地把它圈起来吗?
提前谢谢
我把这里的大多数问题都提到了array,但没有任何帮助
它看起来很简单,但不起作用。如果问题不正确,请对其进行注释。您可以使用一个更简单的工具来完成此操作 结果:
int[] arr = new int[] { 2, 3, 4, 5, 6, 7, 8 };
arr = Arrays.stream(arr).filter(n -> n%2!=0).toArray();
如果无法使用流,以下是一种使代码正常工作的方法:
{3, 5, 7}
请注意,如果某个元素已被删除,则不会增加索引,因为所有后续元素刚刚移回一个位置。您必须更改代码,因为从数组中删除数字时,不必增加索引计数器:
int index = 0;
while (index < arr.length) {
if (arr[index] % 2 == 0) {
arr = ArrayUtils.remove(arr, index);
} else {
++index;
}
}
在提交我的答案后,我看到您将最初的帖子改为只包含Java1.7,而我的帖子是针对1.8的。我只是想提一下 可以使用Arrays.stream将数组转换为流。 可以通过使用Lambda函数调用流方法进行筛选。 然后调用toArray将其转换回数组
int index = 0;
for (int whit : arr) {
if (whit % 2 == 0)
arr = ArrayUtils.remove(arr, index);
else
index++;
}
使用for循环,您可以执行以下操作:
import java.util.Arrays;
int[] arr = new int[] { 2, 3, 4, 5, 6, 7, 8 };
arr = Arrays.stream(arr).filter(a->a%2==0).toArray();
System.out.println(Arrays.toString(arr));
您还可以使用do while循环:
int[] arr = new int[]{2, 3, 4, 5, 6, 7, 8};
for (int index = 0; index < arr.length; index++) {
int whit = arr[index];
if (whit % 2 == 0) {
arr = ArrayUtils.remove(arr, index);
index--;
}
}
remove方法将所有后续元素向左移动,因此索引变得不相关,并且您将引用一个不存在的索引。这个问题将以另一种方式帮助您完成:您可以从右到左迭代数组,将index设置为arr.length-1,并在循环中使用index-减少它。这样,向左移动将不再是一个问题,因为所有移动的元素都已经由循环处理。谢谢兄弟。刚才更新了版本的问题。应该在1.7中。很抱歉给您带来不便。@Noobie OK。我在回答中给出了另一种方法。删除一个元素后,这将跳过一个元素,因为每次索引都会增加,而所有后续元素都会向左移动。谢谢@khelwood。编辑它。您的答案while循环更清晰。删除一个元素后,这将跳过一个元素,因为索引每次都会增加,并且所有后续元素都会向左移动。很抱歉,忘记了else块。尽管如此,如果数组按特定顺序排列:2、3、4、5、6、7、8,它还是可以工作的
int[] arr = new int[]{2, 3, 4, 5, 6, 7, 8};
for (int index = 0; index < arr.length; index++) {
int whit = arr[index];
if (whit % 2 == 0) {
arr = ArrayUtils.remove(arr, index);
index--;
}
}
int[] arr = new int[]{2, 3, 4, 5, 6, 7, 8};
int index = 0;
do{
if (arr[index] % 2 == 0) {
arr = ArrayUtils.remove(arr, index);
} else {
index++;
}
}while(index < arr.length);