Java List collection method and code analysis of traversal process


Collection element frame

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]
  }
}

Method running example

//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]
     */

The List collection is an indexed collection, and cross-border issues should be considered.

Some high-frequency interview questions collected in the latest 2020 (all organized into documents), there are many dry goods, including mysql, netty, spring, thread, spring cloud, jvm, source code, algorithm and other detailed explanations, as well as detailed learning plans, interviews Question sorting, etc. For those who need to obtain these contents, please add Q like: 11604713672

Guess you like

Origin blog.csdn.net/weixin_51495453/article/details/113900209