java遍历list问题?
巴扎黑
巴扎黑 2017-04-17 16:51:29
[Java讨论组]
巴扎黑
巴扎黑

全部回复(3)
ringa_lee

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).

ringa_lee

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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号