Java_基础—List集合的特有功能概述和测试
package com.soar.list;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings({ "rawtypes", "unused","unchecked" })
public class Demo1_List {
/*
* * A:List集合的特有功能概述
* void add(int index,E element)
* E remove(int index)
* E get(int index)
* E set(int index,E element)
*/
public static void main(String[] args) {
//add();
//remove();
//demo_remove();
//bianLi();
//set();
}
private static void set() {
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.set(1, "z"); //将指定位置的元素进行修改
System.out.println(list); //[a, z, c, d]
}
private static void bianLi() {
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
//Object obj1 = list.get(2);
//System.out.println(obj1);
//通过索引遍历List集合
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
private static void demo_remove() {
List list = new ArrayList();
list.add(111);
list.add(222);
list.add(333);
list.remove(111); //删除的时候不会自动装箱,把111当作索引
System.out.println(list); //删除时出现错误 Index: 111, Size: 3
}
private static void remove() {
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
Object obj = list.remove(1); //通过索引删除元素,将被删除的元素返回
System.out.println(obj);
System.out.println(list);
}
private static void add() {
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
//list.add(1,"e");
//System.out.println(list); //[a, e, b, c, d]
//list.add(10,"z");
//System.out.println(list); //当存储时使用不存在的索引时就会出现索引异常
list.add(4,"f"); //index <= size 并且 index>=0 都不会报异常
System.out.println(list);
}
}