Java List集合方法及遍历过程代码解析


集合元素框架

public class ListDemo02 {
  public static void main(String[] args) {
    //创建集合对象
    List<String> list = new ArrayList<String>();

    //添加元素
    list.add("hello");
    list.add("world");
    list.add("java");

    //输出集合对象
    System.out.println(list); //[hello, world, java]
  }
}

方法运行实例

//void add(int index, E element) : 在此集合中的指定位置插入指定的元素
    list.add(1,"javaee"); //[hello, javaee, world, java]
    list.add(11,"j2ee");  //IndexOutOfBoundsException


//E remove(int index):删除指定索引处的元素,返回被删除的元素
    System.out.println(list.remove(1));
    /*
        world
        [hello, java]
     */


//E set(int index,E element):修改指定索引处的元素,返回被修改的元素
    System.out.println(list.set(1,"javaee"));
    /*
        world
        [hello, javaee, java]
     */


//E get(int index):返回指定索引处的元素
    System.out.println(list.get(1));
    /*
        world
        [hello, world, java]
     */
//用for循环改进遍历
    for (int i = 0; i<list.size();i++){
      String s = list.get(i);
      System.out.println(s);
    }
    /*
      hello
      world
      java
      [hello, world, java]
     */

List集合是带索引的集合,要考虑越界问题。


最新2020整理收集的一些高频面试题(都整理成文档),有很多干货,包含mysql,netty,spring,线程,spring cloud、jvm、源码、算法等详细讲解,也有详细的学习规划图,面试题整理等,需要获取这些内容的朋友请加Q君样:11604713672

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容