首页 > java遍历list问题?

java遍历list问题?


        for (int i = 0; i <= max+1; i++) {
            list.add(i,0);
        }

        int c=0;
        for (Interval l : airplanes) {

            int start = l.start;
            int end = l.end;

            c++;
            System.out.println("第"+c+"次遍历开始");

            System.out.println("init data in ("+start+" , "+end+")");

            for (int i = start; i < end; i++) {

                list.add(i, list.get(i)+1);
                System.out.println("end ("+i+" <=> "+list.get(i)+")");
            }
        }
        return Collections.max(list);

Interval的构造器 是

public Interval(int start, int end) {
        this.start = start;
        this.end = end;
    }



为什么,index为5(6也有这样的问题)的list在第三次遍历的时候被初始化为2,在第4次遍历的时候,不应该被增加到3的麽?

Class AbstractList<E>中 add 方法的文档:

public void add(int index,E element)
Inserts the specified element at the specified position in this list. Shifts the element currently at
that position (if any) and any subsequent elements to the right (adds one to their indices).


List.add 方法是用来增加元素的,不是用来增加元素的值的,你完全没搞清楚就用。
修改元素的值要用 List.set 方法


我写了一段代码,展示了add的效果,希望对你能知道自己哪错了

package com.iot.test;


import java.util.ArrayList;
import java.util.List;


public class HelloWorld {


    public static void main(String[] args) {
        System.out.println("Hello world");
        List list = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++) {
            list.add(i,0);
        }

        System.out.println("before ,size:"+list.size());
        System.out.println(list);

        for (int i = 0; i < 10; i++) {

            list.add(i, (Integer)list.get(i)+1);
            System.out.println("end ("+i+" <=> "+list.get(i)+")");
        }

        System.out.println("after ,size:"+list.size());
        System.out.println(list);

    }

}

------------------输出----------------

Hello world
before ,size:10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
end (0 <=> 1)
end (1 <=> 1)
end (2 <=> 1)
end (3 <=> 1)
end (4 <=> 1)
end (5 <=> 1)
end (6 <=> 1)
end (7 <=> 1)
end (8 <=> 1)
end (9 <=> 1)
after ,size:20
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Process finished with exit code 0
【热门文章】
【热门文章】