[英]IndexOutOfBoundsException when using an enhanced for-loop
My enhanced for-loop returns an IndexOutOfBoundsException when I try to run this: 当我尝试运行以下代码时,我的增强型for循环返回IndexOutOfBoundsException:
public static ArrayList<Double> multipliser(ArrayList<Double> listen, int multi) {
for(double elementer : listen) {
listen.set((int) elementer, listen.get((int) elementer * multi));
}
return listen;
It works flawlessly with an good old for-loop: 它可以与旧的for循环完美配合:
for(int i = 0; i < listen.size(); i++) {
listen.set(i, listen.get(i) * multi);
}
return listen;
What am I missing? 我想念什么?
listen.get((int) elementer * multi)
is not the same as 与...不同
listen.get(i)*multi
Similarly in the set
. 同样在
set
。
But an easier way to multiply everything in the list by a constant in-place (in Java 8+) is: 但是,将列表中的所有内容乘以一个常数就位的简单方法(在Java 8+中)是:
listen.replaceAll(x -> x * multi);
The easiest way pre-Java 8 is to use a ListIterator
: Java 8之前的最简单方法是使用
ListIterator
:
for (ListIterator<Double> it = listen.listIterator(); it.hasNext();) {
it.set(it.next() * multi);
}
(Note that this is roughly how the default implementation of Collection.replaceAll
looks in Java 8+). (请注意,这大致是
Collection.replaceAll
的默认实现在Java 8+中的外观)。
In your "enhanced for" loop you're setting your elements at the index corresponding to their value instead of the index of the current loop iteration. 在“增强”循环中,将元素设置为与元素值相对应的索引,而不是当前循环迭代的索引。
Generally speaking I would discourage you to edit a list you're looping on or an object that was passed as an argument. 一般来说,我不鼓励您编辑要循环播放的列表或作为参数传递的对象。 You should create a new list to return instead:
您应该创建一个新列表以返回:
List<Double> result = new ArrayList<>();
for (double elementer : listen) {
result.add(elementer * multi);
}
return result;
Also use interfaces ( List
) in method signatures, not implementations ( ArrayList
): 还要在方法签名中使用接口(
List
),而不要在实现中使用接口( ArrayList
):
public static List<Double> multipliser(List<Double> listen, int multi) {
You can even try this instead which is smaller and so 2017+ (Java 8+): 您甚至可以尝试使用较小的方法,所以2017+(Java 8+):
return listen.stream().map(x -> x * multi).collect(Collectors.toList());
Or even replaceAll()
as Andy Turner suggested. 甚至按Andy Turner的建议
replaceAll()
。
Thank you all very much! 非常感谢大家! I understand now how I was erroneously using the elements and not the index.
我现在了解我是如何错误地使用元素而不是索引。 The code that works (far from optimal) looks like this:
有效的代码(远非最佳)如下所示:
public static ArrayList<Double> multipliser(ArrayList<Double> listen, int multi){
int i = 0;
for(double elementer : listen) {
listen.set(i, elementer*multi);
i++;
}
return listen;
Thanks everyone and have a great weekend! 谢谢大家,度过一个愉快的周末!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.