# 问题:

``````import java.util.*;

public static void main(String []args){
ArrayList <Integer> list = new ArrayList<>(Arrays.asList(10,20,30));

}

public static void add(ArrayList<Integer> list) {
for (int i = list.size() - 1; i >= 0; i--) {
if (i % 2 == 0) {
} else {
}
}
System.out.println(list);
}

}
``````

Expected output: [20, 10, 20, 30, 30, 10]

Actual output: [20, 10, 20, 30, 30, 20]

So I don't understand why, for the last index, when i = 0, 20 is added at the end of the list, which should be 10 as far as I'm concerned.

# 回答1:

Let's see what happens with each loop. Start: `[10, 20, 30]`.

• i = 2

The expression `i % 2` is `0`, so the element at index 2 (`30`) is appended to the end of the list. The list is now `[10, 20, 30, 30]`.

• i = 1

The expression `i % 2` is `1`, so the element at index 1 (`20`) is inserted at the beginning of the list. The list is now `[20, 10, 20, 30, 30]`. Note that `20` is now at the beginning of the list.

• i = 0

The expression `i % 2` is `0`, so the element at index 0 (`20`) is appended to the end of the list. The list is now `[20, 10, 20, 30, 30, 20]`. Note that `20` is appended, not `10`, because `10` is no longer at the beginning of the list, `20` is.

# 回答2:

You're operating on a list, that you're iterating through, which almost never is a good idea. Better would be to use create a new `List` and change the reference of it or simply use the new one:

``````List<Integer> result = new ArrayList<>();
for (int i = list.size() - 1; i >= 0; i--) {
if (i % 2 == 0) {
} else {
}
}
System.out.println(result);
``````
• 发表于 2019-03-21 04:09
• 阅读 ( 120 )
• 分类：sof

## 作家榜 »

1. 小编 文章