一點一點看JDK源碼(二)java.util.Listhtml
liuyuhang原創,未經容許進制轉載java
本文舉例使用的是JDK8的API編程
1.綜述多線程
List譯爲表,一覽表,列表,目錄,名單,有種index的意味在裏頭app
編程語言中的List是強調線性,能夠簡單的視爲一個雙向串行的集合編程語言
List的特點是在結婚的任何位置增長或 刪除元素都比較快,自己並不僅是隨機存取。ide
同時,List是衆多語言中都提供的經常使用類庫之一。函數
java.util.List是一個接口,該接口繼承了Collection接口,所以一樣方法,做爲接口只是定義規範不一樣。工具
實際的不一樣要看獨特的定義或獨特的實現才能夠。post
2.關注點
對List的關注,更多的是傾向於其實現類的關注,不單單是該接口定義的規範或List自己的特性
而是對實現類的具體關注。
根據List的類註釋中的@see,發現如下的關注點
關聯的關注點應該主要只有這些,這些都並不是源碼自己的部分。
對於Collection的剖析,請看我上一篇文章
3.源碼剖析
先上List源碼,去掉原doc註釋,與Collection中重複的部分再也不說起,只對特有的增長註釋。
1 public interface List<E> extends Collection<E> { 2 3 /** 4 * 定義addAll方法,從某個index開始插入指定集合實例 5 */ 6 boolean addAll(int index, Collection<? extends E> c); 7 8 /** 9 * 定義removeAll方法,從某個index開始刪除指定集合實例 10 */ 11 boolean removeAll(Collection<?> c); 12 13 /** 14 * 定義removeAll方法,從某個index開始刪除指定集合實例 15 */ 16 boolean retainAll(Collection<?> c); 17 18 /** 19 * jdk1.8新增 20 * 大意爲: 21 * 定義replaceAll方法,根據傳遞參數的函數式,傳遞內容是接口類型 22 * 該接口定義了operator函數,該函數傳遞給Objects.requireNonNull進行判斷 23 * 匹配成功則進行set值進行替換,使用List迭代器進行迭代替換 24 * @since 1.8 25 */ 26 default void replaceAll(UnaryOperator<E> operator) { 27 Objects.requireNonNull(operator); 28 final ListIterator<E> li = this.listIterator(); 29 while (li.hasNext()) { 30 li.set(operator.apply(li.next())); 31 } 32 } 33 34 /** 35 * jdk1.8新增 36 * 大意爲: 37 * 定義sort方法,根據傳遞參數的函數式,傳遞內容是接口類型 38 * 該接口定義了Comparator函數,該函數傳遞給Arrays.sort進行判斷並排序 39 40 * 並根據排序結果,使用迭代器迭代並從新set進List 41 * @since 1.8 42 */ 43 @SuppressWarnings({"unchecked", "rawtypes"}) 44 default void sort(Comparator<? super E> c) { 45 Object[] a = this.toArray(); 46 Arrays.sort(a, (Comparator) c); 47 ListIterator<E> i = this.listIterator(); 48 for (Object e : a) { 49 i.next(); 50 i.set((E) e); 51 } 52 } 53 54 /** 55 * List要求,定義get方法,獲取指定index的值 56 */ 57 E get(int index); 58 59 /** 60 * List要求,定義set方法,在指定index的元素設置爲目標元素 61 */ 62 E set(int index, E element); 63 64 /** 65 * List要求,定義add方法,在指定index添加指定元素 66 */ 67 void add(int index, E element); 68 69 /** 70 * List要求,定義remove方法,從指定的index刪除該元素並從新調整List 71 */ 72 E remove(int index); 73 74 /** 75 * List要求,定義indexOf方法,正序查詢指定元素第一次出現的index序號 76 */ 77 int indexOf(Object o); 78 79 /** 80 * List要求,定義lastIndexOf方法,倒敘查詢指定元素第一次出現的的index序號 81 */ 82 int lastIndexOf(Object o); 83 84 /** 85 * List要求,定義ListIterator迭代器方法,獲取該List的迭代器 86 */ 87 ListIterator<E> listIterator(); 88 89 /** 90 * List要求,定義ListIterator迭代器方法,獲取從指定index開始的指定迭代器 91 */ 92 ListIterator<E> listIterator(int index); 93 94 /** 95 * List要求,定義subList方法,從起始和結束index拆分出新的list 96 */ 97 List<E> subList(int fromIndex, int toIndex); 98 99 /** 100 * jdk1.8新增 101 * 大意爲: 102 * 根據當前的list內容進行排序,進行迭代器拆分,拆分紅新的迭代器 103 * 用於多線程迭代使用 104 * @since 1.8 105 */ 106 @Override 107 default Spliterator<E> spliterator() { 108 return Spliterators.spliterator(this, Spliterator.ORDERED); 109 }
去掉了從Collection中繼承的方法之後,List有一些獨特的方法,無論是add,set,remove,sub等等。
List接口中定義的這些方法特色是直接和index相關,因爲因爲是有序的,因此index至關於一種搜索方式
所以List有對指定元素進行操做方便的特色。
下一篇更新的文章將對ArrayList,Vector,LinkedList,進行統一特色解析
完畢,以上!