摘要:容器相關的操作及其源碼分析說明本文是基于分析的。有哪些抽取出來的工具類。即對于反轉方式如下替換值查找在出現的最小位置。查找在出現的最大位置。即返回的和原在元素上保持一致,但不可修改。
容器相關的操作及其源碼分析 說明
1、本文是基于JDK 7 分析的。JDK 8 待我工作了得好好研究下。Lambda、Stream。
2、因為個人能力有限,只能以模仿的形式+自己的理解寫筆記。如有不對的地方還請諒解。
3、記錄的比較亂,但是對自己加深印象還是蠻有作用的。
4、筆記放github了,有興趣的可以看看。喜歡的可以點個star。
5、讀過源碼的可以快速瀏覽一遍,也能加深自己的理解。
6、源碼是個好東東,各種編碼技巧,再次佩服老外!!!
7、下一個主題是容器List,gogogo。感覺可以的話可以關注哈
Collections來源于網上(感謝大佬的制作)
先放一張整體的容器圖,在了解容器之前,我們先來看看容器的工具類Collections.我有一個習慣,就是每看一個項目之前會先去commons.util包中看看。有哪些抽取出來的工具類。在正式進入主題之前先考大家一個問題,synchronizedList()、synchronizedSet()、synchronizedMap() 這三個方法有啥作用呢?當然讓他們變為同步的咯,那怎么變成的呢?其實我也想知道。
首先主要注意的是不會看全部方法,只會看一些常用的,多個重載的只看一個。
正式看之前我們需要知道這個類構造方法是私有的,也就是不能被實例化,方法是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 collection hierarchy. A collection * represents a group of objects, known as its elements. Some * collections allow duplicate elements and others do not. Some are ordered * and others unordered. The JDK does not provide any direct * implementations of this interface: it provides implementations of more * specific subinterfaces like Set and List. This interface * is typically used to pass collections around and manipulate them where * maximum generality is desired. */ public interface Collectionextends Iterable { int size(); boolean isEmpty(); boolean contains(Object o); Iterator iterator(); Object[] toArray(); 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)
/** * 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 * mutually comparable (that is, {@code e1.compareTo(e2)} * must not throw a {@code ClassCastException} for any elements * {@code e1} and {@code e2} in the list). */ public staticbinarySearch> void sort(List list) { Object[] a = list.toArray(); //首先進來就變成一個數組,需要注意的是調用List,然而List底下還有具體的實現呢. Arrays.sort(a); //在調用Arrays.sort()方法排序(默認升序ASC) ListIterator i = list.listIterator(); 雙端迭代器,只能用于List哦, for (int j=0; j listIterator() { return new ListItr(0); //注意這里new了一個內部類,到ArrayList時再看。 //題外話:之前聽某培訓機構的課說內部類無卵用。 } //可我見諒很多啊Spring的,TreeNode,鏈表里,事件里... private class ListItr extends Itr implements ListIterator { 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 iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr */ private class Itr implements Iterator { 終點在這里 public boolean hasNext() {} public E next() {} public void remove() {} }
需要注意的是 the list must be sorted,默認是升序的。如果包含多個,則不能確保被找到。
第二段大概意思就是該方法是log(n)的,前提你的實現RandomAccess接口啊,或者這個數非常大,則就會執行下面的那個但這里變成了 O(n)遍歷,log(n)比較。
/** * 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 staticint binarySearch(List extends Comparable super T>> list, T key) { //首先判斷list是否是RandomAccess的實例,在判斷list的大小是否小于5000這個閥值, //注意丨丨(跟我讀gun gun,不信你試試在 ) if (list instanceof RandomAccess || list.size() 我在思考看那個比較好:
首先想說明的是,我在Arrays類里已經分析過二分查找了,所以會簡化一下。主要找之間的區別。點這里直接到Binary
private staticreverseint 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 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 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.* * 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
>1; i swap(重點) /** * 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使用默認的隨機數,隨機打算指定的列表,SHUFFLE_THRESHOLD默認為5,
/** * Randomly permutes the specified list using a default source of * randomness. All permutations occur with approximately equal * likelihood.*/ 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.
* 大概意思為使用指定的隨機數源,假設`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
fill填充 用指定元素替換指定列表中的元素,線性執行的。FILL_THRESHOLD為25
/** * Replaces all of the elements of the specified list with the specified * element.* * This method runs in linear time. */ public static
void fill(List super T> list, T obj) { int size = list.size(); if (size < FILL_THRESHOLD || list instanceof RandomAccess) { for (int i=0; i itr = list.listIterator(); for (int i=0; i min 返回給定集合的最小元素,自然順序排序。
/** * Returns the minimum element of the given collection, according to the * natural ordering of its elements. All elements in the * collection must implement the Comparable interface. * Furthermore, all elements in the collection must be mutually * comparable (that is, e1.compareTo(e2) must not throw a * ClassCastException for any elements e1 and * e2 in the collection).max*/ public static
> 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 staticrotate> 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 i will be * the element previously at index (i - distance) mod * list.size(), for all values of i between 0 * and list.size()-1, inclusive. (This method has no effect on * the size of the list.) * * 解釋在這里,指定列表較小,或者實現了`RandomAccess`接口,則調用rotate1, * 指定的列表非常大,沒有實現接口,則調用subList分為兩個列表 * *replaceAllIf 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 * RandomAccess interface, this implementation breaks the * list into two sublist views around index -distance mod size. */ 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
void rotate1(List 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) 替換值
indexOfSubList查找target在source出現的最小位置。該方法的實現也是通常的挨個元素比較法,沒有太大創新。不同的是對于迭代式的list,當最后判斷出source的當前位置開始不是target時,需要回退。
lastIndexOfSubList查找target在source出現的最大位置。
實現方式和indexOfSubList相似,只是從后面往前查找。上面介紹了一些算法功能的實現,接下來我們看其他的
unmodifiable處于安全性考慮,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 * UnsupportedOperationException.synchronized*/ public static
Collection unmodifiableCollection(Collection extends T> c) { return new UnmodifiableCollection<>(c); } ------------------------------------------------------------------------------------ static class UnmodifiableCollection implements Collection , 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 iterator() { return new Iterator () { 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 Set unmodifiableSet(Set extends T> s) { return new UnmodifiableSet<>(s); //直接new,這個又繼承了UnmodifiableCollection } --------------------------------------------------------------------------------- static class UnmodifiableSet extends UnmodifiableCollection implements Set , 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 SortedSet unmodifiableSortedSet(SortedSet s) { return new UnmodifiableSortedSet<>(s); } public static List unmodifiableList(List extends T> list) { return (list instanceof RandomAccess ? new UnmodifiableRandomAccessList<>(list) : new UnmodifiableList<>(list)); } public static Map 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 * all access to the backing collection is accomplished * through the returned collection.*/ public static
Collection synchronizedCollection(Collection c) { return new SynchronizedCollection<>(c); } static Collection synchronizedCollection(Collection c, Object mutex) { return new SynchronizedCollection<>(c, mutex); } ------------------------------------------------------------------------------- /** * 需要注意的是這里new了個內部類, */ static class SynchronizedCollection implements Collection , Serializable { private static final long serialVersionUID = 3053995032091335093L; final Collection c; // Backing Collection //原來的引用 final Object mutex; // Object on which to synchronize,要同步的對象 SynchronizedCollection(Collection c) { 構造方法初始化,讓c變成當前的引用 if (c==null) throw new NullPointerException(); this.c = c; mutex = this; } SynchronizedCollection(Collection c, Object mutex) { this.c = c; this.mutex = mutex; } //使用mutex 實現互斥,然后仍是調用原Collection相應的方法。 public int size() { synchronized (mutex) {return c.size();} } //略 public Iterator 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 SynchronizedSetextends SynchronizedCollection implements Set { private static final long serialVersionUID = 487447009682186044L; SynchronizedSet(Set s) { super(s); } SynchronizedSet(Set 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 * all access to the backing map is accomplished * through the returned map.* * @param m the map to be "wrapped" in a synchronized map. * @return a synchronized view of the specified map. */ public static
Map synchronizedMap(Map m) { return new SynchronizedMap<>(m); } ------------------------------------------------------------------------------- /** * @serial include */ private static class SynchronizedMap implements Map , 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 implements Map.Entry {...} private final class KeySet extends AbstractSet {...} ---------------------------------------------------------------------------------- private transient Set keySet = null; private transient Set > entrySet = null; private transient Collection values = null; public Set keySet() { synchronized (mutex) { if (keySet==null) keySet = new SynchronizedSet<>(m.keySet(), mutex); return keySet; } } public Set > entrySet() { synchronized (mutex) { if (entrySet==null) //重新new,如果等于null entrySet = new SynchronizedSet<>(m.entrySet(), mutex); return entrySet; } } } 中間的內容等看Map的時候在看
Checked該系列方法保證增刪的數據都是同類型的。返回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 * guaranteed that the collection cannot contain an incorrectly * typed element. */ public staticcheckedSetCollection checkedCollection(Collection c, Class type) { return new CheckedCollection<>(c, type); } ------------------------------------------------------------------------ static class CheckedCollection implements Collection , Serializable { final Collection c; final Class type; void typeCheck(Object o) { //類型檢查 if (o != null && !type.isInstance(o)) throw new ClassCastException(badElementMsg(o)); } CheckedCollection(Collection c, Class 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 iterator() { final Iterator it = c.iterator(); return new Iterator () { 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 guaranteed that the * set cannot contain an incorrectly typed element. * *EmptyA discussion of the use of dynamically typesafe views may be * found in the documentation for the {@link #checkedCollection * checkedCollection} method. * *
The returned set will be serializable if the specified set is * serializable. * *
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
Set checkedSet(Set s, Class type) { return new CheckedSet<>(s, type); } /** * @serial include */ static class CheckedSet extends CheckedCollection implements Set , Serializable { private static final long serialVersionUID = 4694047833775013803L; CheckedSet(Set s, Class 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. * *This example illustrates the type-safe way to obtain an empty set: *
* Set*/ public static finals = Collections.emptySet(); * Set emptySet() { return (Set ) EMPTY_SET; } /** * @serial include */ private static class EmptySet extends AbstractSet implements Serializable { public Iterator iterator() { return emptyIterator(); } public int size() {return 0;} //為 0 public boolean isEmpty() {return true;} //為空嗎?是啊 public boolean contains(Object obj) {return false;} public T[] toArray(T[] a) { if (a.length > 0) a[0] = null; //注定為null啊 return a; } } 其他大同小異,不多介紹了
Singleton保證生成的Collection只包含一個元素。看看人家底層是怎么實現的
public staticList singletonList(T o) { return new SingletonList<>(o); } ------------------------------------------------------------------------------- private static class SingletonList extends AbstractList implements RandomAccess, Serializable { private final E element; SingletonList(E obj) {element = obj;} public Iterator 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。。。
frequency統計某個元素在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); }disjoint如果兩個指定的集合沒有相同元素則返回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; }addAll添加指定的元素到指定集合中。 @return true 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 * c.addAll(Arrays.asList(elements)), but this method is likely * to run significantly faster under most implementations. */ @SafeVarargs public staticAsLIFOQueueboolean 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 add is mapped to push, * remove is mapped to pop and so on. This * view can be useful when you would like to use a method * requiring a Queue but you need Lifo ordering. */ public staticQueue asLifoQueue(Deque deque) { return new AsLIFOQueue<>(deque); } ------------------------------------------------------------------- /** * @serial include */ static class AsLIFOQueue extends AbstractQueue implements Queue , Serializable { private static final long serialVersionUID = 1802017725587941708L; private final Deque q; AsLIFOQueue(Deque 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 iterator() { return q.iterator(); } public Object[] toArray() { return q.toArray(); } public 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~收獲蠻大的。
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/68714.html
摘要:不同與其它中間件框架,中有大量的業務代碼,它向我們展示了大神是如何寫業務代碼的依賴的層次結構,如何進行基礎包配置,以及工具類編寫,可以稱之為之最佳實踐。代碼參考視圖解析器,這里的配置指的是不檢查頭,而且默認請求為格式。 不同與其它中間件框架,Apollo中有大量的業務代碼,它向我們展示了大神是如何寫業務代碼的:maven依賴的層次結構,如何進行基礎包配置,以及工具類編寫,可以稱之為sp...
摘要:容器相關的操作及其源碼分析說明本文是基于分析的。通常,我們通過迭代器來遍歷集合。是接口所特有的,在接口中,通過返回一個對象。為了偷懶啊,底層使用了迭代器。即返回的和原在元素上保持一致,但不可修改。 容器相關的操作及其源碼分析 說明 1、本文是基于JDK 7 分析的。JDK 8 待我工作了得好好研究下。Lambda、Stream。 2、本文會貼出大量的官方注釋文檔,強迫自己學英語,篇幅...
摘要:我的是忙碌的一年,從年初備戰實習春招,年三十都在死磕源碼,三月份經歷了阿里五次面試,四月順利收到實習。因為我心理很清楚,我的目標是阿里。所以在收到阿里之后的那晚,我重新規劃了接下來的學習計劃,將我的短期目標更新成拿下阿里轉正。 我的2017是忙碌的一年,從年初備戰實習春招,年三十都在死磕JDK源碼,三月份經歷了阿里五次面試,四月順利收到實習offer。然后五月懷著忐忑的心情開始了螞蟻金...
摘要:容器相關的操作及其源碼分析說明本文是基于分析的。源碼是個好東東,各種編碼技巧,再次佩服老外下一個主題是容器,。在了解容器之前我們先來看下重點的數據吧,還有工具類。第一段話說明返回一個指定數組的固定列表。 容器相關的操作及其源碼分析 說明 1、本文是基于JDK 7 分析的。JDK 8 待我工作了得好好研究下。Lambda、Stream。 2、因為個人能力有限,只能以模仿的形式+自己的理...
閱讀 1949·2023-04-26 01:59
閱讀 3264·2021-10-11 11:07
閱讀 3295·2021-09-22 15:43
閱讀 3374·2021-09-02 15:21
閱讀 2549·2021-09-01 10:49
閱讀 901·2019-08-29 15:15
閱讀 3089·2019-08-29 13:59
閱讀 2829·2019-08-26 13:36