使用增强的for循环时IndexOutOfBoundsException

时间:2018-02-02 15:28:26

标签: java for-loop

当我尝试运行时,我的增强型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;

它与完美的旧循环完美配合:

for(int i = 0; i < listen.size(); i++) {
    listen.set(i, listen.get(i) * multi);
}
return listen;

我错过了什么?

3 个答案:

答案 0 :(得分:5)

listen.get((int) elementer * multi)

不同
listen.get(i)*multi

同样在set

但是,通过就地常量(在Java 8+中)将列表中的所有内容相乘的更简单方法是:

listen.replaceAll(x -> x * multi);

Java 8之前最简单的方法是使用ListIterator

for (ListIterator<Double> it = listen.listIterator(); it.hasNext();) {
  it.set(it.next() * multi);
}

(请注意,这大致是{8}中Collection.replaceAll的默认实现看起来如何。

答案 1 :(得分:1)

在“增强for”循环中,您将元素设置在与其值相对应的索引处,而不是当前循环迭代的索引。

一般来说,我不鼓励你编辑你正在循环的列表或作为参数传递的对象。您应该创建一个新列表来返回:

if

在方法签名中使用接口(List),而不是实现(ArrayList):

List<Double> result = new ArrayList<>();
for (double elementer : listen) {
    result.add(elementer * multi);
}
return result;

你甚至可以试试这个更小的所以2017+(Java 8 +):

public static List<Double> multipliser(List<Double> listen, int multi) {

甚至replaceAll()建议为Andy Turner

答案 2 :(得分:0)

非常感谢你们!我现在明白我是如何错误地使用元素而不是索引。有效的代码(远非最佳)看起来像这样:

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;

谢谢大家,祝周末愉快!