Adding integers to an ArrayList depending on the modulus of their indexes

问题: import java.util.*; public class AddingIntegers{ public static void main(String []args){ ArrayList <Integer> list = new ArrayList<>(Arrays.asList(...

问题:

import java.util.*;
public class AddingIntegers{

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

        add(list);
     }


public static void add(ArrayList<Integer> list) {
    for (int i = list.size() - 1; i >= 0; i--) {
        if (i % 2 == 0) {
            list.add(list.get(i));
        } else {
            list.add(0, list.get(i));
        }
    }
    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) {
        result.add(list.get(i));
    } else {
        result.add(0, list.get(i));
    }
}
System.out.println(result);
  • 发表于 2019-03-21 04:09
  • 阅读 ( 120 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除