猿问

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的麽?


温温酱
浏览 446回答 3
3回答

慕容森

Class AbstractList<E>中 add 方法的文档:public void add(int index,E element)&nbsp;Inserts the specified element at the specified position in this list. Shifts the element currently atthat position (if any) and any subsequent elements to the right (adds one to their indices).

Helenr

ist.add 方法是用来增加元素的,不是用来增加元素的值的,你完全没搞清楚就用。修改元素的值要用 List.set 方法
随时随地看视频慕课网APP

相关分类

Java
我要回答