List接口中常用的方法 import java.util.ArrayList; import java.util.List; public class Demo01 { public static void main(String[] args) { List<String> list=new ArrayList<String>(); list.add("a"); list.add("b"); //指定位置添加元素 list.add(1,"c"); System.out.println(list);//遍历 [a, c, b] //遍历 for(int i=0;i<list.size();i++){ System.out.println(list.get(i)); //a c b } //删除指定位置 String str=list.remove(1); System.out.println(str);//c System.out.println(list);//[a, b] //替换指定位置上的元素 list.set(1, "z"); System.out.println(list);//[a, z] } } Iterator的并发修改异常 import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Demo02 { public static void main(String[] args) { List<String> list=new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); //获取迭代器对象 Iterator<String> it=list.iterator(); //并发修改异常 while(it.hasNext()){ String s=it.next(); if(s.equals("b")){ list.add("d"); } //System.out.println(it.next()); } } }
List集合存储数据的结构 堆栈、队列、数组、链表 LinkedList集合 import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Demo03 { public static void main(String[] args) { method1(); method2(); method3(); } public static void method1(){ LinkedList<Integer> list=new LinkedList<Integer>(); /*list.add(1); list.add(2); list.addFirst(3); list.addFirst(4); list.addLast(5);*///[4, 3, 1, 2, 5] list.addLast(1);//相对于当前集合 list.addLast(2); list.add(3); list.addFirst(4); list.addFirst(5); System.out.println(list);//[5, 4, 1, 2, 3] System.out.println(list.getFirst());//首元素 5 System.out.println(list.getLast());//尾元素 3 list.removeLast();//删除尾元素 System.out.println(list);//[5, 4, 1, 2] System.out.println(list.getLast());//2 } public static void method2(){ LinkedList<Integer> list=new LinkedList<Integer>(); list.push(1); list.push(2); list.push(3); list.push(4); //模拟弹栈的效果 if(!list.isEmpty()){//如果集合不为空 System.out.println(list.pop());//4 System.out.println(list.pop());//3 System.out.println(list.pop());//2 System.out.println(list.pop());//1 } } //查询集合中指定元素出现的次数 public static void method3(){ List<String> list = new ArrayList<>(); list.add("a"); list.add("a"); list.add("a"); list.add("b"); list.add("b"); list.add("c"); list.add("d"); list.add("d"); list.add("d"); list.add("d"); list.add("d"); System.out.println(list);//遍历集合 [a, a, a, b, b, c, d, d, d, d, d] int count1=Collections.frequency(list,"a");//指定元素 int count2=Collections.frequency(list,"b"); int count3=Collections.frequency(list,"c"); int count4=Collections.frequency(list,"d"); int count5=Collections.frequency(list,"e"); System.out.println(count1);//查询出现次数 3 System.out.println(count2);//2 System.out.println(count3);//1 System.out.println(count4);//5 System.out.println(count5);//0 } }