1 package cn.zmh.LinkedList; 2 3 import java.util.Iterator; 4 import java.util.LinkedList; 5 6 public class LinkendListDemo1 { 7 public static void main(String[] args) { 8 fun2(); 9 fun1_3(); 10 11 12 } 13 14 // 1 addFirst();从前面添加 addLast(); 从后面添加 15 public static void fun1() { 16 LinkedList<String> link = new LinkedList<>(); 17 link.addFirst("钱"); 18 link.addFirst("赵"); 19 link.addLast("孙"); 20 link.addLast("李"); 21 Iterator<String> it = link.iterator(); 22 while (it.hasNext()) { 23 String s = it.next(); 24 System.out.println(s); 25 } 26 } 27 // 1_1 addFirst();从前面添加 getFirst();获取第一个元素 28 // Iterator 迭代器 29 public static void fun1_1() { 30 LinkedList<String> link = new LinkedList<>(); 31 link.addFirst("李白1"); 32 link.addFirst("李白2"); 33 link.addFirst("李白3"); 34 //获取第一个集合元素(李白3); 35 String first = link.getFirst(); 36 System.out.println(first); 37 Iterator<String> it = link.iterator(); 38 while (it.hasNext()) { 39 String s = it.next(); 40 System.out.println(s); 41 } 42 } 43 // 1_2 集合转数组 44 public static void fun1_2() { 45 LinkedList<String> link = new LinkedList<>(); 46 link.addFirst("a1"); 47 link.addFirst("a2"); 48 link.addFirst("a3"); 49 System.out.println(link); 50 Object[] array = link.toArray(); 51 //for循环 52 for (int i=0;i<array.length;i++){ 53 System.out.println(array[i]); 54 } 55 //迭代器 56 Iterator<String> it = link.iterator(); 57 while(it.hasNext()){ 58 String s = it.next(); 59 System.out.println(s); 60 } 61 } 62 public static void fun1_3(){ 63 LinkedList<String> link = new LinkedList<>(); 64 link.add("a1"); 65 link.add("a2"); 66 link.add("a3"); 67 System.out.println(link); 68 //删除第一个 69 String rem = link.removeFirst(); 70 //删除最后一个 71 String rem1 = link.removeLast(); 72 System.out.println("被删除的:"+rem+" "+rem1); 73 System.out.println(link); 74 } 75 // 2 getFirst();获取第一个 getLast(); 获取最后一个 76 public static void fun2() { 77 LinkedList<String> link = new LinkedList<>(); 78 link.add("张飞1"); 79 link.add("刘备2"); 80 link.add("关羽3"); 81 //isEmpty() 判断集合是否为空 在进行操作 82 if (!link.isEmpty()) { 83 String first = link.getFirst(); 84 System.out.println(first); 85 } 86 } 87 // 3 removeFirst(); removeLast();删除功能 88 public static void fun3() { 89 LinkedList<String> link = new LinkedList<>(); 90 link.add("每当我听到雨声"); 91 link.add("就行听到了心中的迷茫"); 92 String s = link.removeFirst(); 93 System.out.println("被删除的:" + s); 94 System.out.println(link); 95 } 96 }