來源於網上(感謝大佬的製做)java
先放一張總體的容器圖,在瞭解容器以前,咱們先來看看容器的工具類Collections
.我有一個習慣,就是每看一個項目以前會先去commons.util包中看看。有哪些抽取出來的工具類。在正式進入主題以前先考你們一個問題,synchronizedList()
、synchronizedSet()
、synchronizedMap()
這三個方法有啥做用呢?固然讓他們變爲同步的咯,那怎麼變成的呢?其實我也想知道。git
首先主要注意的是不會看所有方法,只會看一些經常使用的,多個重載的只看一個。github
正式看以前咱們須要知道這個類構造方法是私有的,也就是不能被實例化,方法是static 只能類名.方法();算法
接着就定義了一些靜態常量,大致意思就是List有兩個實現,一個是隨機的List(RandomAccess),另一個是順序的(sequential)。隨機訪問在變量在較小的順序List中有較好的性能。就是一些調優參數,根據他們的經驗。反正是定義了各類閾值,看方法的時候在介紹做用。這種技巧叫命名參數,也能夠寫成SQL語句。方便更改。數組
public class Collections { // Suppresses default constructor, ensuring non-instantiability. private Collections() { //被私有化了, } // Algorithms(算法) /* * Tuning parameters for algorithms - Many of the List algorithms have * two implementations, one of which is appropriate for RandomAccess * lists, the other for "sequential." Often, the random access variant * yields better performance on small sequential access lists. */ private static final int BINARYSEARCH_THRESHOLD = 5000; private static final int REVERSE_THRESHOLD = 18; private static final int SHUFFLE_THRESHOLD = 5; private static final int FILL_THRESHOLD = 25; private static final int ROTATE_THRESHOLD = 100; private static final int COPY_THRESHOLD = 10; private static final int REPLACEALL_THRESHOLD = 11; private static final int INDEXOFSUBLIST_THRESHOLD = 35; } -----------------------------插一點----------------------------------------------- 容器的根接口,組要注意的是這裏只是定義,具體的實如今子類中,全部容器共有的方法。(Map除外啊) /** * The root interface in the <i>collection hierarchy</i>. A collection * represents a group of objects, known as its <i>elements</i>. Some * collections allow duplicate elements and others do not. Some are ordered * and others unordered. The JDK does not provide any <i>direct</i> * implementations of this interface: it provides implementations of more * specific subinterfaces like <tt>Set</tt> and <tt>List</tt>. This interface * is typically used to pass collections around and manipulate them where * maximum generality is desired. */ public interface Collection<E> extends Iterable<E> { int size(); boolean isEmpty(); boolean contains(Object o); Iterator<E> iterator(); Object[] toArray(); <T> T[] toArray(T[] a); boolean add(E e); boolean remove(Object o); boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); boolean removeAll(Collection<?> c); boolean retainAll(Collection<?> c); void clear(); boolean equals(Object o); int hashCode(); }
須要注意的是一個是實現了comparable接口,裏面有compareTo()方法,另一個自定義Comparator
的compare()方法。安全
首先進來就變成一個數組,須要注意的是調用List,然而List底下還有具體的實現呢.
在調用Arrays.sort()方法排序(默認升序ASC)app
/** * Sorts the specified list into ascending order, according to the * {@linkplain Comparable natural ordering} of its elements. * All elements in the list must implement the {@link Comparable} * interface. Furthermore, all elements in the list must be * <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} * must not throw a {@code ClassCastException} for any elements * {@code e1} and {@code e2} in the list). */ public static <T extends Comparable<? super T>> void sort(List<T> list) { Object[] a = list.toArray(); //首先進來就變成一個數組,須要注意的是調用List,然而List底下還有具體的實現呢. Arrays.sort(a); //在調用Arrays.sort()方法排序(默認升序ASC) ListIterator<T> i = list.listIterator(); 雙端迭代器,只能用於List哦, for (int j=0; j<a.length; j++) { i.next(); //檢查是否有下一個, i.set((T)a[j]); //進行設置, } } ----------------------------------------------------------------------------------- public ListIterator<E> listIterator() { return new ListItr(0); //注意這裏new了一個內部類,到ArrayList時再看。 //題外話:以前聽某培訓機構的課說內部類無卵用。 } //可我見諒不少啊Spring的,TreeNode,鏈表裏,事件裏... private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); } public boolean hasPrevious() { } public int nextIndex() { } public int previousIndex() { } public E previous() {} public void set(E e) {} public void add(E e) {} } ---------------------繼續,你們看出區別了嗎,下一個主題在將------------------------- public Iterator<E> iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr */ private class Itr implements Iterator<E> { 終點在這裏 public boolean hasNext() {} public E next() {} public void remove() {} }
須要注意的是 the list must be sorted,默認是升序的。若是包含多個,則不能確保被找到。dom
第二段大概意思就是該方法是log(n)的,前提你的實現RandomAccess
接口啊,或者這個數很是大,則就會執行下面的那個但這裏變成了 O(n)遍歷,log(n)比較。ide
/** * Searches the specified list for the specified object using the binary * search algorithm. The list must be sorted into ascending order * according to the {@linkplain Comparable natural ordering} of its * elements (as by the {@link #sort(List)} method) prior to making this * call. If it is not sorted, the results are undefined. If the list * contains multiple elements equal to the specified object, there is no * guarantee which one will be found. * *-這裏解釋了緣由 *This method runs in log(n) time for a "random access" list (which * provides near-constant-time positional access). If the specified list * does not implement the {@link RandomAccess} interface and is large, * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. */ public static <T>int binarySearch(List<? extends Comparable<? super T>> list, T key) { //首先判斷list是不是RandomAccess的實例,在判斷list的大小是否小於5000這個閥值, //注意丨丨(跟我讀gun gun,不信你試試在 ) if (list instanceof RandomAccess || list.size()<BINARYSEARCH_THRESHOLD) return Collections.indexedBinarySearch(list, key); else return Collections.iteratorBinarySearch(list, key); }
我在思考看那個比較好:工具
首先想說明的是,我在Arrays類裏已經分析過二分查找了,因此會簡化一下。主要找之間的區別。點這裏直接到Binary
private static <T> int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key) { int low = 0; int high = list.size()-1; while (low <= high) { int mid = (low + high) >>> 1; Comparable<? super T> midVal = list.get(mid); int cmp = midVal.compareTo(key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found } -----------------------------------區別,多了個i-------------------------------------------- private static <T> int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key) { ListIterator<? extends Comparable<? super T>> i = list.listIterator(); Comparable<? super T> midVal = get(i, mid); } ---------------------------------------------------------------- /** *大概意思就是從新定位list的迭代器,獲取第i個元素。 * Gets the ith element from the given list by repositioning the specified * list listIterator. * */ private static <T> T get(ListIterator<? extends T> i, int index) { T obj = null; int pos = i.nextIndex(); if (pos <= index) { //看下i的下一個元素中間位置的哪邊?小於在左邊get(i, mid); do { obj = i.next(); //這這裏至少會執行一次。 } while (pos++ < index); //若是這裏爲真,則上面那條一直執行。 } else { do { obj = i.previous(); // } while (--pos > index); //直到--到等於minVal爲止 } return obj; }
反轉指定列表的順序,須要注意的是時間複雜度爲線性的。
能夠看到,當 List 支持隨機訪問時,能夠直接從頭開始,第一個元素和最後一個元素交換位置,一直交換到中間位置。
swap就是交換兩個位置,還有注意反轉閥值爲18.右移位就是除2,j爲最後的一個REVERSE_THRESHOLD
爲18
/** * Reverses the order of the elements in the specified list.<p> * * This method runs in linear time. */ public static void reverse(List<?> list) { int size = list.size(); if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) { //swap就是交換兩個位置,還有注意反轉閥值爲18. for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--) swap(list, i, j); //這裏調用的是----下面的方法 } else { ListIterator fwd = list.listIterator(); ListIterator rev = list.listIterator(size); for (int i=0, mid=list.size()>>1; i<mid; i++) { Object tmp = fwd.next(); //獲取fwd的下一個,看成臨時的 fwd.set(rev.previous()); //獲取反轉列表的前一個設置到fwd rev.set(tmp); //在設置臨時的 // rev.set(fwd.next()); //循環交替設置, } fwd ------- } rev:------- }
/** * Swaps the elements at the specified positions in the specified list. * (If the specified positions are equal, invoking this method leaves * the list unchanged.) */ public static void swap(List<?> list, int i, int j) { //L.get(i)返回位置i上的元素, //l.set(j, l.get(i)) 將i上的元素設置給j,同時因爲l.set(i,E)返回這個位置上以前的元素,能夠返回原來在j上的元素 //而後在設置給i final List l = list; l.set(i, l.set(j, l.get(i))); } -------------------------------------------------------------------------------- /** * Swaps the two specified elements in the specified array. * 這個簡單那 */ private static void swap(Object[] arr, int i, int j) { Object tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } -------------------------------------------------------------------------------- private static void swap(Object[] arr, int i, int j) { arr[i] = num[i] + arr[j]; arr[j] = num[i] - arr[j]; num[i] = num[i] -arr[j]; } ---------------------------------------------------------------------------------- private static void swap(Object[] arr, int i, int j) { num[i] = num[i]^arr[j]; max = num[i]^arr[j]; num[i] = num[i] ^ arr[j]; }
使用默認的隨機數,隨機打算指定的列表,SHUFFLE_THRESHOLD
默認爲5,
/** * Randomly permutes the specified list using a default source of * randomness. All permutations occur with approximately equal * likelihood.<p> */ public static void shuffle(List<?> list) { Random rnd = r; if (rnd == null) r = rnd = new Random(); shuffle(list, rnd); //調用下面這個方法。 } private static Random r; -------------------------------------------------------------------------------------- /** * Randomly permute the specified list using the specified source of * randomness. All permutations occur with equal likelihood * assuming that the source of randomness is fair.<p> * 大概意思爲使用指定的隨機數源,假設`the source of randomness`是公平的,全部排列都是相等的。 */ public static void shuffle(List<?> list, Random rnd) { int size = list.size(); if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) { for (int i=size; i>1; i--) swap(list, i-1, rnd.nextInt(i)); //先判斷是否超過閥值,成立則交換。 } else { Object arr[] = list.toArray(); // Shuffle array for (int i=size; i>1; i--) swap(arr, i-1, rnd.nextInt(i)); // Dump array back into list //將數組返回到列表中 ListIterator it = list.listIterator(); for (int i=0; i<arr.length; i++) { it.next(); it.set(arr[i]); } } }
用指定元素替換指定列表中的元素,線性執行的。FILL_THRESHOLD
爲25
/** * Replaces all of the elements of the specified list with the specified * element. <p> * * This method runs in linear time. */ public static <T> void fill(List<? super T> list, T obj) { int size = list.size(); if (size < FILL_THRESHOLD || list instanceof RandomAccess) { for (int i=0; i<size; i++) list.set(i, obj); } else { ListIterator<? super T> itr = list.listIterator(); for (int i=0; i<size; i++) { itr.next(); itr.set(obj); } } }
返回給定集合的最小元素,天然順序排序。
/** * Returns the minimum element of the given collection, according to the * <i>natural ordering</i> of its elements. All elements in the * collection must implement the <tt>Comparable</tt> interface. * Furthermore, all elements in the collection must be <i>mutually * comparable</i> (that is, <tt>e1.compareTo(e2)</tt> must not throw a * <tt>ClassCastException</tt> for any elements <tt>e1</tt> and * <tt>e2</tt> in the collection).<p> */ public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); //做爲候補,先拿出一個 while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) < 0) //比較二者哪一個小 candidate = next; //將i位置的下一個做爲候補隊員 } return candidate; }
返回集合中最大的元素,和上面惟一的卻別就是next.compareTo(candidate) > 0
變爲大於號了。
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) > 0) candidate = next; } return candidate; }
按照給定的步長旋轉指定的列表,一樣分爲隨機存取的List和迭代式後移。ROTATE_THRESHOLD
默認爲100
這裏的思想就是若是列表太大則分爲兩個子列表進行反轉。
/** * Rotates the elements in the specified list by the specified distance. * After calling this method, the element at index <tt>i</tt> will be * the element previously at index <tt>(i - distance)</tt> mod * <tt>list.size()</tt>, for all values of <tt>i</tt> between <tt>0</tt> * and <tt>list.size()-1</tt>, inclusive. (This method has no effect on * the size of the list.) * * 解釋在這裏,指定列表較小,或者實現了`RandomAccess`接口,則調用rotate1, * 指定的列表很是大,沒有實現接口,則調用subList分爲兩個列表 * * <p>If the specified list is small or implements the {@link * RandomAccess} interface, this implementation exchanges the first * element into the location it should go, and then repeatedly exchanges * the displaced element into the location it should go until a displaced * element is swapped into the first element. If necessary, the process * is repeated on the second and successive elements, until the rotation * is complete. If the specified list is large and doesn't implement the * <tt>RandomAccess</tt> interface, this implementation breaks the * list into two sublist views around index <tt>-distance mod size</tt>. */ public static void rotate(List<?> list, int distance) { if (list instanceof RandomAccess || list.size() < ROTATE_THRESHOLD) rotate1(list, distance); else rotate2(list, distance); } private static <T> void rotate1(List<T> list, int distance) {看不懂....} --------------------------性能好與上面--------------------------------------------- private static void rotate2(List<?> list, int distance) { int size = list.size(); if (size == 0) return; int mid = -distance % size; if (mid < 0) mid += size; //控制中間位置 if (mid == 0) return; reverse(list.subList(0, mid)); //截取0到中間位置。 reverse(list.subList(mid, size)); reverse(list); } --------------------------------------------------------------------------------- 即對於(1,2,3,4,5,6), distance=2. 反轉方式以下(1,2,3,4,5,6)–>(4,3,2,1,5,6)–>(4,3,2,1,6,5)–>(5,6,1,2,3,4)
替換值
查找target在source出現的最小位置。該方法的實現也是一般的挨個元素比較法,沒有太大創新。不一樣的是對於迭代式的list,當最後判斷出source的當前位置開始不是target時,須要回退。
查找target在source出現的最大位置。
實現方式和indexOfSubList類似,只是從後面往前查找。
上面介紹了一些算法功能的實現,接下來咱們看其餘的
處於安全性考慮,Collections提供了大量額外的非功能性方法,其中之一即是生成原Collection的不可修改視圖。
即返回的Collection和原Collection在元素上保持一致,但不可修改。
該實現主要是經過重寫add,remove等方法來實現的。即在可能修改的方法中直接拋出異常。
the collection to be "wrapped" in a synchronized collection.
a synchronized view of the specified collection.
其實很簡單,這裏使用了裝飾器模式,還有就是內部類+mutex(互斥)。而後全部的繼承UnmodifiableCollection
增長裏面沒有的方法。
/** * Returns an unmodifiable view of the specified collection. This method * allows modules to provide users with "read-only" access to internal * collections. Query operations on the returned collection "read through" * to the specified collection, and attempts to modify the returned * collection, whether direct or via its iterator, result in an * <tt>UnsupportedOperationException</tt>.<p> */ public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) { return new UnmodifiableCollection<>(c); } ------------------------------------------------------------------------------------ static class UnmodifiableCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 1820017752578914078L; final Collection<? extends E> c; UnmodifiableCollection(Collection<? extends E> c) { if (c==null) throw new NullPointerException(); //空指針異常 this.c = c; } public int size() {return c.size();} public boolean isEmpty() {return c.isEmpty();} public boolean contains(Object o) {return c.contains(o);} public String toString() {return c.toString();} public Iterator<E> iterator() { return new Iterator<E>() { private final Iterator<? extends E> i = c.iterator(); public boolean hasNext() {return i.hasNext();} public E next() {return i.next();} public void remove() { throw new UnsupportedOperationException(); } }; } public boolean add(E e) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean containsAll(Collection<?> coll) { return c.containsAll(coll); } //。。。。 } ---------------------------------------------------------------------------------- public static <T> Set<T> unmodifiableSet(Set<? extends T> s) { return new UnmodifiableSet<>(s); //直接new,這個又繼承了UnmodifiableCollection } --------------------------------------------------------------------------------- static class UnmodifiableSet<E> extends UnmodifiableCollection<E> implements Set<E>, Serializable { private static final long serialVersionUID = -9215047833775013803L; UnmodifiableSet(Set<? extends E> s) {super(s);} public boolean equals(Object o) {return o == this || c.equals(o);} public int hashCode() {return c.hashCode();} } --------------------------------------------------------------------------------- public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<T> s) { return new UnmodifiableSortedSet<>(s); } public static <T> List<T> unmodifiableList(List<? extends T> list) { return (list instanceof RandomAccess ? new UnmodifiableRandomAccessList<>(list) : new UnmodifiableList<>(list)); } public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m) { return new UnmodifiableMap<>(m); }
是時候回答剛開始的問題了。有些是參考了這篇博文點一點
可能你在使用java的Collection集合時就聽過過Collection是非線程安全的,但通常不多告訴你如何實現現成安全,因而就有了這個方法
synchronized方法返回線程安全的原Collection。該方法保證線程安全不出意外還是經過synchronized關鍵字來實現的。
In order to guarantee serial access,
須要注意的是這裏new了個內部類,
/** * Returns a synchronized (thread-safe) collection backed by the specified * collection. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing collection is accomplished * through the returned collection.<p> */ public static <T> Collection<T> synchronizedCollection(Collection<T> c) { return new SynchronizedCollection<>(c); } static <T> Collection<T> synchronizedCollection(Collection<T> c, Object mutex) { return new SynchronizedCollection<>(c, mutex); } ------------------------------------------------------------------------------- /** * 須要注意的是這裏new了個內部類, */ static class SynchronizedCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 3053995032091335093L; final Collection<E> c; // Backing Collection //原來的引用 final Object mutex; // Object on which to synchronize,要同步的對象 SynchronizedCollection(Collection<E> c) { 構造方法初始化,讓c變成當前的引用 if (c==null) throw new NullPointerException(); this.c = c; mutex = this; } SynchronizedCollection(Collection<E> c, Object mutex) { this.c = c; this.mutex = mutex; } //使用mutex 實現互斥,而後還是調用原Collection相應的方法。 public int size() { synchronized (mutex) {return c.size();} } //略 public Iterator<E> iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add(E e) { synchronized (mutex) {return c.add(e);} } public boolean remove(Object o) { synchronized (mutex) {return c.remove(o);} } } ---------------------------------------------------------------------------- * × * It is imperative that the user manually synchronize on the returned * collection when iterating over it: * < * Collection c = Collections.synchronizedCollection(myCollection); * //上下兩個方法均可以實現現成同步 * synchronized (c) { * Iterator i = c.iterator(); // Must be in the synchronized block * while (i.hasNext()) * foo(i.next()); * } *
咱們來看一個代碼少的吧,其實實現套路都差很少。須要注意的是super
,這裏直接使用了SynchronizedCollection
中的mytex實現互斥鎖。父類中沒有equals和hashCode()方法,因此。
static class SynchronizedSet<E> extends SynchronizedCollection<E> implements Set<E> { private static final long serialVersionUID = 487447009682186044L; SynchronizedSet(Set<E> s) { super(s); } SynchronizedSet(Set<E> s, Object mutex) { super(s, mutex); } public boolean equals(Object o) { if (this == o) return true; synchronized (mutex) {return c.equals(o);} } public int hashCode() { synchronized (mutex) {return c.hashCode();} } }
咱們接着來看看Map是如何實現的,其實思想是同樣的,內部類+mutex,返回a synchronized view of the specified map.
由於Map中
/** * Returns a synchronized (thread-safe) map backed by the specified * map. In order to guarantee serial access, it is critical that * <strong>all</strong> access to the backing map is accomplished * through the returned map.<p> * * @param m the map to be "wrapped" in a synchronized map. * @return a synchronized view of the specified map. */ public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) { return new SynchronizedMap<>(m); } ------------------------------------------------------------------------------- /** * @serial include */ private static class SynchronizedMap<K,V> implements Map<K,V>, Serializable { public V get(Object key) { synchronized (mutex) {return m.get(key);} } public V put(K key, V value) { synchronized (mutex) {return m.put(key, value);} } ----------------------------注意這裏----------------------------------------------------- static class Entry<K,V> implements Map.Entry<K,V> {...} private final class KeySet extends AbstractSet<K> {...} ---------------------------------------------------------------------------------- private transient Set<K> keySet = null; private transient Set<Map.Entry<K,V>> entrySet = null; private transient Collection<V> values = null; public Set<K> keySet() { synchronized (mutex) { if (keySet==null) keySet = new SynchronizedSet<>(m.keySet(), mutex); return keySet; } } public Set<Map.Entry<K,V>> entrySet() { synchronized (mutex) { if (entrySet==null) //從新new,若是等於null entrySet = new SynchronizedSet<>(m.entrySet(), mutex); return entrySet; } } }
中間的內容等看Map的時候在看
該系列方法保證增刪的數據都是同類型的。返回a dynamically typesafe view of the specified collection
/** * Returns a dynamically typesafe view of the specified collection. * Any attempt to insert an element of the wrong type will result in an * immediate {@link ClassCastException}. Assuming a collection * contains no incorrectly typed elements prior to the time a * dynamically typesafe view is generated, and that all subsequent * access to the collection takes place through the view, it is * <i>guaranteed</i> that the collection cannot contain an incorrectly * typed element. */ public static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type) { return new CheckedCollection<>(c, type); } ------------------------------------------------------------------------ static class CheckedCollection<E> implements Collection<E>, Serializable { final Collection<E> c; final Class<E> type; void typeCheck(Object o) { //類型檢查 if (o != null && !type.isInstance(o)) throw new ClassCastException(badElementMsg(o)); } CheckedCollection(Collection<E> c, Class<E> type) { if (c==null || type == null) throw new NullPointerException(); this.c = c; this.type = type; } public boolean contains(Object o) { return c.contains(o); } public Object[] toArray() { return c.toArray(); } public boolean remove(Object o) { return c.remove(o); } public Iterator<E> iterator() { final Iterator<E> it = c.iterator(); return new Iterator<E>() { public boolean hasNext() { return it.hasNext(); } public E next() { return it.next(); } public void remove() { it.remove(); }}; } public boolean add(E e) { typeCheck(e); return c.add(e); } //省略了一些
/** * Returns a dynamically typesafe view of the specified set. * Any attempt to insert an element of the wrong type will result in * an immediate {@link ClassCastException}. Assuming a set contains * no incorrectly typed elements prior to the time a dynamically typesafe * view is generated, and that all subsequent access to the set * takes place through the view, it is <i>guaranteed</i> that the * set cannot contain an incorrectly typed element. * * <p>A discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * * <p>The returned set will be serializable if the specified set is * serializable. * * <p>Since {@code null} is considered to be a value of any reference * type, the returned set permits insertion of null elements whenever * the backing set does. * * @param s the set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold * @return a dynamically typesafe view of the specified set * @since 1.5 */ public static <E> Set<E> checkedSet(Set<E> s, Class<E> type) { return new CheckedSet<>(s, type); } /** * @serial include */ static class CheckedSet<E> extends CheckedCollection<E> implements Set<E>, Serializable { private static final long serialVersionUID = 4694047833775013803L; CheckedSet(Set<E> s, Class<E> elementType) { super(s, elementType); } public boolean equals(Object o) { return o == this || c.equals(o); } public int hashCode() { return c.hashCode(); } }
保證返回一個空的Collection。
/** * Returns the empty set (immutable). This set is serializable. * Unlike the like-named field, this method is parameterized. * * <p>This example illustrates the type-safe way to obtain an empty set: * <pre> * Set<String> s = Collections.emptySet(); * </pre> */ public static final <T> Set<T> emptySet() { return (Set<T>) EMPTY_SET; } /** * @serial include */ private static class EmptySet<E> extends AbstractSet<E> implements Serializable { public Iterator<E> iterator() { return emptyIterator(); } public int size() {return 0;} //爲 0 public boolean isEmpty() {return true;} //爲空嗎?是啊 public boolean contains(Object obj) {return false;} public <T> T[] toArray(T[] a) { if (a.length > 0) a[0] = null; //註定爲null啊 return a; } }
其餘大同小異,很少介紹了
保證生成的Collection只包含一個元素。看看人家底層是怎麼實現的
public static <T> List<T> singletonList(T o) { return new SingletonList<>(o); } ------------------------------------------------------------------------------- private static class SingletonList<E> extends AbstractList<E> implements RandomAccess, Serializable { private final E element; SingletonList(E obj) {element = obj;} public Iterator<E> iterator() { return singletonIterator(element); } public int size() {return 1;} //直接返回1, public boolean contains(Object obj) {return eq(obj, element);} public E get(int index) { if (index != 0) //之間給你拋個異常,不服不服?Size等於 throw new IndexOutOfBoundsException("Index: "+index+", Size: 1"); return element; } }
提及異常了,咱們看看異常體系的結構圖.注意設計思想,若是咱們要設計能夠直接來個BaseException繼承·RuntimeException
。其餘類在實現這個BaseException
。其餘的也相似如:BaseDAO、BaseAction。。。
統計某個元素在Collection中出現的頻率
/** * Returns the number of elements in the specified collection equal to the * specified object. */ public static int frequency(Collection<?> c, Object o) { int result = 0; if (o == null) { for (Object e : c) if (e == null) //這裏判斷null出現了幾回。 result++; } else { for (Object e : c) if (o.equals(e)) //用queals()方法 result++; //result++ } return result; } ----------------------------補充---------------------------------------------------- /** * Returns true if the specified arguments are equal, or both null. */ static boolean eq(Object o1, Object o2) { return o1==null ? o2==null : o1.equals(o2); }
若是兩個指定的集合沒有相同元素則返回true。
/** * Returns {@code true} if the two specified collections have no * elements in common. */ public static boolean disjoint(Collection<?> c1, Collection<?> c2) { // The collection to be used for contains(). Collection<?> contains = c2; // The collection to be iterated. Collection<?> iterate = c1; if (c1 instanceof Set) { iterate = c2; contains = c1; } else if (!(c2 instanceof Set)) { int c1size = c1.size(); int c2size = c2.size(); if (c1size == 0 || c2size == 0) { // At least one collection is empty. Nothing will match. return true; } if (c1size > c2size) { iterate = c2; contains = c1; } } for (Object e : iterate) { if (contains.contains(e)) { // Found a common element. Collections are not disjoint. return false; } } // No common elements were found. //檢查了一遍沒有相同的,則 return true; }
添加指定的元素到指定集合中。 @return <tt>true</tt> if the collection changed as a result of the call
也能夠是數組和Arrays.asList
效果同樣。
/** * Adds all of the specified elements to the specified collection. * Elements to be added may be specified individually or as an array. * The behavior of this convenience method is identical to that of * <tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely * to run significantly faster under most implementations. */ @SafeVarargs public static <T> boolean addAll(Collection<? super T> c, T... elements) { boolean result = false; for (T element : elements) result |= c.add(element); //難道這就是傳說中的丨(gun)嗎? return result; //實際上是給result添加一個屬性值,也就是`c.add(element)` }
返回一個後進先出的雙端隊列,add映射到push,remove映射到pop,當你須要一個後進先出的隊列時這個方法很是有用。
/** * Returns a view of a {@link Deque} as a Last-in-first-out (Lifo) * {@link Queue}. Method <tt>add</tt> is mapped to <tt>push</tt>, * <tt>remove</tt> is mapped to <tt>pop</tt> and so on. This * view can be useful when you would like to use a method * requiring a <tt>Queue</tt> but you need Lifo ordering. */ public static <T> Queue<T> asLifoQueue(Deque<T> deque) { return new AsLIFOQueue<>(deque); } ------------------------------------------------------------------- /** * @serial include */ static class AsLIFOQueue<E> extends AbstractQueue<E> implements Queue<E>, Serializable { private static final long serialVersionUID = 1802017725587941708L; private final Deque<E> q; AsLIFOQueue(Deque<E> q) { this.q = q; } public boolean add(E e) { q.addFirst(e); return true; } public boolean offer(E e) { return q.offerFirst(e); } public E poll() { return q.pollFirst(); } public E remove() { return q.removeFirst(); } public E peek() { return q.peekFirst(); } public E element() { return q.getFirst(); } public void clear() { q.clear(); } public int size() { return q.size(); } public boolean isEmpty() { return q.isEmpty(); } public boolean contains(Object o) { return q.contains(o); } public boolean remove(Object o) { return q.remove(o); } public Iterator<E> iterator() { return q.iterator(); } public Object[] toArray() { return q.toArray(); } public <T> T[] toArray(T[] a) { return q.toArray(a); } public String toString() { return q.toString(); } public boolean containsAll(Collection<?> c) {return q.containsAll(c);} public boolean removeAll(Collection<?> c) {return q.removeAll(c);} public boolean retainAll(Collection<?> c) {return q.retainAll(c);} // We use inherited addAll; forwarding addAll would be wrong 轉發的時候可能會出錯。 }
Collections
到這裏算是結束了,中午時再看來看看Collection中的方法,其具體實如今子子類中。
晚安,早安。gogogo~收穫蠻大的。