List集合是Collection集合子类型,继承了Collection中所有的功能,比Collection约束更加详细、严谨。
List继承了Collection中所有方法,元素具备索引特性,因此新增了一些含有索引的特有方法。
public void add(int index, E element)
将指定的元素,添加到该集合中的指定位置上。如果指定位置上已存在元素,则会把已存在元素向后移动一位。
例子
List<String> list = new LinkedList<>(); list.add("hello"); list.add("world"); System.out.println(list); // [hello, world] list.add(1, "hi"); // [hello, hi, world]
public E get(int index)
返回集合中指定位置的元素
例子
List<String> list = new LinkedList<>(); list.add("hello"); list.add("world"); System.out.println(list.get(0)); // hello
public E remove(int index)
移除列表中指定位置的元素,返回的是被移除的元素
例子
List<String> list = new LinkedList<>(); list.add("hello"); list.add("world"); System.out.println(list); // [hello, world] list.remove(0); System.out.println(list); // [world]
public E set(int index, E element)
用指定元素替换集合中指定位置的元素,返回值是更新前的元素。
例子
List<String> list = new LinkedList<>(); list.add("hello"); list.add("world"); String str = list.set(0, "hi"); System.out.println(str); // hello System.out.println(list); // [hi, world]
原文:https://www.cnblogs.com/xulinjun/p/14775878.html