摘要:容器相關的操作及其源碼分析說明本文是基于分析的。通常,我們通過迭代器來遍歷集合。是接口所特有的,在接口中,通過返回一個對象。為了偷懶啊,底層使用了迭代器。即返回的和原在元素上保持一致,但不可修改。
容器相關的操作及其源碼分析 說明
1、本文是基于JDK 7 分析的。JDK 8 待我工作了得好好研究下。Lambda、Stream。
2、本文會貼出大量的官方注釋文檔,強迫自己學英語,篇幅比較長,還請諒解。
3、筆記放github了,有興趣的可以看看。喜歡的可以點個star。
4、讀過源碼的可以快速瀏覽一遍,也能加深自己的理解。
5、源碼是個好東東,各種編碼技巧,再次佩服老外?。?!
6、其中方法會插一些測試用例,并不是完整的
Collections來源于網(wǎng)上(感謝大佬的制作)
容器,就是可以容納其他Java對象的對象,在正式進入容器之前,我們先來看幾個接口的定義,后學的方法會用到。
需要注意的是,Collection繼承的是Iterable
Implementing this interface allows an object to be the target of the "foreach" statement 最為關鍵那,實現(xiàn)此接口的都可以用 foreach進行遍歷,為啥啊。為了偷懶啊,foreeach底層使用了迭代器。
重點需要注意的是Iterable
個人感覺泛型 + 反射,能力大過天。要在加一點那就是內(nèi)部類。
Iterableimport java.util.Iterator; /** * Implementing this interface allows an object to be the target of * the "foreach" statement. */ public interface IterableIterator{ /** * Returns an iterator over a set of elements of type T.. */ Iterator iterator(); }
/** * An iterator over a collection. {@code Iterator} takes the place of * {@link Enumeration} in the Java Collections Framework. */ public interface IteratorListIterator{ /** * Returns {@code true} if the iteration has more elements. */ boolean hasNext(); /** * Returns the next element in the iteration. */ E next(); /** * Removes from the underlying collection the last element returned * by this iterator (optional operation). */ void remove(); }
/** * An iterator for lists that allows the programmer * to traverse the list in either direction, modify * the list during iteration, and obtain the iterator"s * current position in the list. */ public interface ListIteratorCollectionextends Iterator { // Query Operations /** * Returns {@code true} if this list iterator has more elements when * traversing the list in the forward direction. */ boolean hasNext(); /** * Returns the next element in the list and advances the cursor position. */ E next(); /** * Returns {@code true} if this list iterator has more elements when * traversing the list in the reverse direction. (In other words, * returns {@code true} if {@link #previous} would return an element * rather than throwing an exception.) */ boolean hasPrevious(); /** * Returns the previous element in the list and moves the cursor * position backwards. This method may be called repeatedly to * iterate through the list backwards, or intermixed with calls to * {@link #next} to go back and forth. */ E previous(); /** * Returns the index of the element that would be returned by a * subsequent call to {@link #next}. (Returns list size if the list * iterator is at the end of the list.) */ int nextIndex(); /** * Returns the index of the element that would be returned by a * subsequent call to {@link #previous}. */ int previousIndex(); /** * Removes from the list the last element that was returned by {@link * #next} or {@link #previous} (optional operation). */ void remove(); /** * Replaces the last element returned by {@link #next} or * {@link #previous} with the specified element (optional operation). */ void set(E e); /** * Inserts the specified element into the list (optional operation). */ void add(E e); }
接下來,我們正式進入主題吧,有些英文不會解釋。
首先看看Collection中具體有哪些方法。
Josh Bloch這位大佬曾是Google的首席架構師,他的Twitter。
9行代碼,索賠超過10億美金,那么每一行代碼價值一億多美金,這也一度被外界解讀為史上最昂貴的代碼之一。
想知道在哪里嗎?上次我們分析了數(shù)組檢查是否越界
/** * Checks that {@code fromIndex} and {@code toIndex} are in * the range and throws an exception if they aren"t. */ private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) { if (fromIndex > toIndex) { throw new IllegalArgumentException( "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); } if (fromIndex < 0) { throw new ArrayIndexOutOfBoundsException(fromIndex); } if (toIndex > arrayLength) { throw new ArrayIndexOutOfBoundsException(toIndex); } }
注意這里使用了泛型,具體的在實現(xiàn)類中,在這里只是定義了一些通用的方法,在抽象類中類中實現(xiàn)。凡是繼承此接口的都可以用。最好的設計理念是中間加入了AbstractCollection,為啥要這么設計呢?因為抽象類天生就是用來被繼承的,你要是實現(xiàn)接口,你必須實現(xiàn)所有的方法,JDK8中加入了默認方法,來看圖。
來源于網(wǎng)上(感謝大佬的制作)
在來看看在IDEA中的結構圖,
public class ArrayList
這樣設計的主要目的是方便擴展,接下來,我們簡單看看AbstractCollection是怎么實現(xiàn)的
/** * 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. * * * @paramAbstractCollectionthe type of elements in this collection //注意泛型 * * @author Josh Bloch * @author Neal Gafter * @since 1.2 */ public interface Collection extends Iterable { // Query Operations /** * Returns the number of elements in this collection. */ int size(); /** * Returns true if this collection contains no elements. */ boolean isEmpty(); /** * Returns true if this collection contains the specified element. */ boolean contains(Object o); /** * Returns an iterator over the elements in this collection. There are no * guarantees concerning the order in which the elements are returned * (unless this collection is an instance of some class that provides a * guarantee). * * @return an Iterator over the elements in this collection */ Iterator iterator(); /** * Returns an array containing all of the elements in this collection. * If this collection makes any guarantees as to what order its elements * are returned by its iterator, this method must return the elements in * the same order. */ Object[] toArray(); // Modification Operations /** * Ensures that this collection contains the specified element (optional * operation). Returns true if this collection changed as a * result of the call. */ boolean add(E e); /** * Removes a single instance of the specified element from this * collection, if it is present (optional operation). */ boolean remove(Object o); // Bulk Operations /** * Returns true if this collection contains all of the elements * in the specified collection. */ boolean containsAll(Collection> c); /** * Adds all of the elements in the specified collection to this collection * (optional operation). The behavior of this operation is undefined if * the specified collection is modified while the operation is in progress. */ boolean addAll(Collection extends E> c); /** * Removes all of this collection"s elements that are also contained in the * specified collection (optional operation). After this call returns, * this collection will contain no elements in common with the specified * collection. */ boolean removeAll(Collection> c); /** * Retains only the elements in this collection that are contained in the * specified collection (optional operation). */ boolean retainAll(Collection> c); /** * Removes all of the elements from this collection (optional operation). * The collection will be empty after this method returns. */ void clear(); /** * Compares the specified object with this collection for equality. */ boolean equals(Object o); /** * Returns the hash code value for this collection. */ int hashCode(); }
to minimize the effort required to implement this interface這里解釋了原因
** * This class provides a skeletal implementation of the Collection * interface, to minimize the effort required to implement this interface.*/ public abstract class AbstractCollection
implements Collection { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected AbstractCollection() { } // Query Operations /** * Returns an iterator over the elements contained in this collection */ public abstract Iterator iterator(); public abstract int size(); --------------------------------------------------------------------------------- /** * This implementation returns size() == 0. */ public boolean isEmpty() { return size() == 0; } /** *
This implementation iterates over the elements in the collection, * checking each element in turn for equality with the specified element. */ public boolean contains(Object o) { Iterator
it = iterator(); //使用迭代器進行遍歷選擇 if (o==null) { while (it.hasNext()) if (it.next()==null) //注意null return true; } else { while (it.hasNext()) if (o.equals(it.next())) //調(diào)用o。qualse()方法。 return true; } return false; //木有,不含夠 //大體思路就是首先判斷傳進來的是否為null,是否還有還一個,下一個等于null,成為返回true。 //傳進來o不等于null,是否還有還一個,下一個等于null,成為返回true。 } --------------------------------------------------------------------------------- /** * {@inheritDoc} * * This implementation returns an array containing all the elements * returned by this collection"s iterator, in the same order, stored in * consecutive elements of the array, starting with index {@code 0}. *
This method is equivalent to: * //方法等同于下面這個, *
{@code * List*/ public Object[] toArray() { // Estimate size of array; be prepared to see more or fewer elements Object[] r = new Object[size()]; Iteratorlist = new ArrayList (size()); * for (E e : this) * list.add(e); * return list.toArray(); * } it = iterator(); for (int i = 0; i < r.length; i++) { if (! it.hasNext()) // fewer elements than expected return Arrays.copyOf(r, i); //這里使用了Arrays.copyOf(),之前講過,此時返回一個空數(shù)組 r[i] = it.next(); //取出下一個放到r[i]中,如if中有一條語句老外一般不用{} } return it.hasNext() ? finishToArray(r, it) : r; //還沒有的元素的話就完成ToArary。 } ------------------------------------------------------------------------------------------ /** *處于安全性考慮,Collections提供了大量額外的非功能性方法,其中之一便是生成原Collection的不可修改視圖。 *即返回的Collection和原Collection在元素上保持一致,但不可修改。 *該實現(xiàn)主要是通過重寫add,remove等方法來實現(xiàn)的。即在可能修改的方法中直接拋出異常。 * This implementation always throws an * UnsupportedOperationException. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} */ public boolean add(E e) { throw new UnsupportedOperationException(); } /** *
This implementation iterates over the collection looking for the * specified element. */ public boolean remove(Object o) { Iterator
it = iterator(); if (o==null) { while (it.hasNext()) { if (it.next()==null) { it.remove(); //和上面contains邏輯差不多 return true; //這里調(diào)用迭代器的remove方法移除 } } } else { while (it.hasNext()) { if (o.equals(it.next())) { it.remove(); //同理 return true; } } } return false; } ------------------------------------------------------------------------------------- // Bulk Operations /** * This implementation iterates over the specified collection, * checking each element returned by the iterator in turn to see * if it"s contained in this collection. */ public boolean containsAll(Collection> c) { for (Object e : c) if (!contains(e)) //這里循環(huán)遍歷,只要一個不包含則fasle。 return false; return true; } /** *
This implementation iterates over the specified collection, and adds * each object returned by the iterator to this collection, in turn. */ public boolean addAll(Collection extends E> c) { boolean modified = false; //使用一個標記 for (E e : c) //這里沒用大括號是不是簡潔多了? if (add(e)) //循環(huán)添加,如果為真,修改modified,返回 modified = true; return modified; } /** *
This implementation iterates over this collection, checking each * element returned by the iterator in turn to see if it"s contained * in the specified collection. */ public boolean removeAll(Collection> c) { boolean modified = false; //修改標記 Iterator> it = iterator(); //使用迭代, while (it.hasNext()) { //判斷是否還有下一個, if (c.contains(it.next())) { //有才能刪除,沒有刪除毛線 it.remove(); modified = true; //刪除之后修改標記, } } return modified; } --------------------------------------------------------------------------- /** *
This implementation iterates over this collection, removing each * element using the Iterator.remove operation. Most * implementations will probably choose to override this method for * efficiency. */ public void clear() { Iterator
it = iterator(); while (it.hasNext()) { it.next(); it.remove(); } } ------------------------------------------------------------------------------- // String conversion /** * Returns a string representation of this collection. The string * representation consists of a list of the collection"s elements in the * order they are returned by its iterator, enclosed in square brackets * ("[]"). * @return a string representation of this collection */ public String toString() { Iterator it = iterator(); if (! it.hasNext()) //沒有下一個直接返回"[]",熟悉吧? return "[]"; StringBuilder sb = new StringBuilder(); 這里使用了StringBuilder追加形式, sb.append("["); for (;;) { //可以這樣寫嗎? E e = it.next(); sb.append(e == this ? "(this Collection)" : e); if (! it.hasNext()) return sb.append("]").toString(); //這里判斷是否沒有元素來。 sb.append(",").append(" "); //[1,2,3,4,5] } }
其實很多類中的方法差不多,只是邏輯上有細微的變化??慈思业拇a,再看看我們自己寫的代碼。
加油吧,希望自己也可以寫出這樣的代碼。gogogo。
接下來我們在看看List中特有的方法,具體的實現(xiàn)在AbstrctList中。和上面重復的就不在多介紹了
List摘抄之前的一些筆記
選擇List的具體實現(xiàn):
1.安全性問題
2.是否頻繁的插入、刪除操作
3.是否存儲后遍歷
-
List接口:1,有序的,2.允許有多個null元素,3、具體的實現(xiàn)類常用的有:ArrayList,Vector,LinkedList
List接口特有的方法,帶有索引的功能
also known as a sequence 通常第一段是重點
/** * An ordered collection (also known as a sequence). The user of this * interface has precise control over where in the list each element is * inserted. The user can access elements by their integer index (position in * the list), and search for elements in the list.AbstrctList* @author Josh Bloch */ public interface List
extends Collection { //省略Collection中的方法 // Positional Access Operations //位置訪問操作 /** * Returns the element at the specified position in this list. 返回指定位置上的元素 */ E get(int index); /** * Replaces the element at the specified position in this list with the * specified element (optional operation). */ E set(int index, E element); /** * Inserts the specified element at the specified position in this list * (optional operation). Shifts the element currently at that position * (if any) and any subsequent elements to the right (adds one to their * indices). */ void add(int index, E element); /** * Removes the element at the specified position in this list (optional * operation). Shifts any subsequent elements to the left (subtracts one * from their indices). Returns the element that was removed from the * list. */ E remove(int index); // Search Operations //查詢操作 /** * Returns the index of the first occurrence of the specified element * in this list, or -1 if this list does not contain the element. *第一次出現(xiàn)的位置,不存在-1 */ int indexOf(Object o); /** * Returns the index of the last occurrence of the specified element * in this list, or -1 if this list does not contain the element. *最后出現(xiàn)的索引位置,不存在則返回-1 */ int lastIndexOf(Object o); // List Iterators /** * Returns a list iterator over the elements in this list (in proper * sequence). */ ListIterator listIterator(); /** * Returns a list iterator over the elements in this list (in proper * sequence), starting at the specified position in the list. * 指定開始的索引 */ ListIterator listIterator(int index); // View /** * Returns a view of the portion of this list between the specified * fromIndex, inclusive, and toIndex, exclusive. * 返回子List的視圖,可能會拋出索引越界異常,需要檢查。也就是用那九行代碼。 */ List subList(int fromIndex, int toIndex); }
接下來我們看看這個具體的實現(xiàn),重復的忽略。這個也是重點,
注意注意的是:
1、LinkedList是繼承AbstractSequentialList的然后他在繼承AbstractList。為啥要這樣設計?留點疑問,待會到LinkdedList的時候講。注意一定看認真看類名。
2、鎖住的是內(nèi)部類,在Collections中定義的,@return an immutable list containing only the specified object
/** * Returns an immutable list containing only the specified object. * The returned list is serializable. */ public staticList singletonList(T o) { return new SingletonList<>(o); } ---------------------------------------------------------------------------------- private static class SingletonList extends AbstractList implements RandomAccess, Serializable { public int size() {return 1;} //直接給你返回1,你服不服? public E get(int index) { if (index != 0) //只要索引不為0就給你拋個異常, throw new IndexOutOfBoundsException("Index: "+index+", Size: 1"); return element; } } --------------------------------回顧--------------------------------------------- public static final List EMPTY_LIST = new EmptyList<>(); /** * Returns the empty list (immutable). */ @SuppressWarnings("unchecked") public static final List emptyList() { return (List ) EMPTY_LIST; } -------------------------------------------------------------------------------- /** * Returns a fixed-size list backed by the specified array. */ public static List asList(T... a) { return new ArrayList<>(a); } private static class ArrayList extends AbstractList implements RandomAccess, java.io.Serializable { public int size() { return a.length; } public E get(int index) { return a[index]; } }
3、ArrayLIst接下來就是我們的真正主題了,
4、注意Vector也是實現(xiàn)AbstractList的(List),他有個子類是Stack因為是同步的,線程安全的。所有效率比較低。
import java.util.LinkedList; public class Stack{ private LinkedList storage = new LinkedList (); public void push(T v) { storage.addFirst(v); } public T peek() { return storage.getFirst(); } public T pop() { return storage.removeFirst(); } public boolean empty() { return storage.isEmpty(); } public String toString() { return storage.toString(); } }
//對方法添加了synchronized以保證線程安全,讀多寫少的情景下建議使用CopyOnWriteArrayList public class Vectorextends AbstractList implements List , RandomAccess, Cloneable, java.io.Serializable{}
以上Vector類不過多介紹,Stack可以先看看, last-in-first-out
(LIFO)后進先出的,先進后出一樣,有五個方法可以操作Vector,
/** * TheStack
class represents a last-in-first-out * (LIFO) stack of objects. It extends class Vector with five * */ publicclass Stackextends Vector { ...}
首先需要注意的是它繼承自AbstractCollection具備了它里面的所有方法,自己又額外添加了一些索引方法的
package java.util; /** * This class provides a skeletal implementation of the {@link List} * interface to minimize the effort required to implement this interface * backed by a "random access" data store (such as an array). For sequential * access data (such as a linked list), {@link AbstractSequentialList} should * be used in preference to this class. */ public abstract class AbstractListiterator(重點)extends AbstractCollection implements List { // Search Operations /** * This implementation first gets a list iterator (with * {@code listIterator()}). Then, it iterates over the list until the * specified element is found or the end of the list is reached. */ public int indexOf(Object o) { ListIterator
it = listIterator(); //注意調(diào)用的是ListIterator if (o==null) { while (it.hasNext()) if (it.next()==null) return it.previousIndex(); //這里返回的是上一個索引位置的。 } else { while (it.hasNext()) if (o.equals(it.next())) return it.previousIndex(); } return -1; } /** * This implementation first gets a list iterator that points to the end * of the list (with {@code listIterator(size())}). */ public int lastIndexOf(Object o) { ListIterator
it = listIterator(size()); if (o==null) { while (it.hasPrevious()) if (it.previous()==null) return it.nextIndex(); //返回下一個位置的索引 } else { while (it.hasPrevious()) if (o.equals(it.previous())) return it.nextIndex(); } return -1; } // Bulk Operations /** * Removes all of the elements from this list (optional operation). * The list will be empty after this call returns. */ public void clear() { removeRange(0, size()); } ------------------------------------------------------------------------------- /** * Removes from this list all of the elements whose index is between * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. * Shifts any succeeding elements to the left (reduces their index). */ protected void removeRange(int fromIndex, int toIndex) { ListIterator it = listIterator(fromIndex); for (int i=0, n=toIndex-fromIndex; i This implementation gets an iterator over the specified collection * and iterates over it, inserting the elements obtained from the * iterator into this list at the appropriate position, one at a time, * using {@code add(int, E)}. */ public boolean addAll(int index, Collection extends E> c) { rangeCheckForAdd(index); //檢查范圍 boolean modified = false; for (E e : c) { add(index++, e); //循環(huán)進行添加, modified = true; //完成之后修改標記 } return modified; } -------------------------------------------------------------------------------- /** * The number of times this list has been structurally modified. * Structural modifications are those that change the size of the * list, or otherwise perturb it in such a fashion that iterations in * progress may yield incorrect results. */ protected transient int modCount = 0; private void rangeCheckForAdd(int index) { if (index < 0 || index > size()) //拋出越界異常, throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } // Comparison and hashing 比較與哈希。 /** * Compares the specified object with this list for equality. Returns * {@code true} if and only if the specified object is also a list, both * lists have the same size, and all corresponding pairs of elements in * the two lists are equal. */ public boolean equals(Object o) { if (o == this) //1.判斷是否是當前對象 return true; if (!(o instanceof List)) //2、是List的實例嗎? return false; ListIterator e1 = listIterator(); ListIterator e2 = ((List) o).listIterator(); while (e1.hasNext() && e2.hasNext()) { //兩個都不能為空, E o1 = e1.next(); Object o2 = e2.next(); if (!(o1==null ? o2==null : o1.equals(o2))) //這里使用了三目運算, return false; } return !(e1.hasNext() || e2.hasNext()); } /** * Returns the hash code value for this list. */ public int hashCode() { int hashCode = 1; for (E e : this) hashCode = 31*hashCode + (e==null ? 0 : e.hashCode()); //31是素數(shù) return hashCode; }
-------------------------之前講過了設計的很精妙------------------------------------ // Iterators /** * Returns an iterator over the elements in this list in proper sequence. */ public Iteratoriterator() { //3 return new Itr(); } /** * This implementation returns {@code listIterator(0)}. */ public ListIterator
listIterator() { return listIterator(0); // 1 } public ListIterator listIterator(final int index) { //2 return new ListItr(index); } ------------------------------------------------------------------------------- private class Itr implements Iterator { //注意這里,實現(xiàn) //4 public boolean hasNext() {..} public E next() {..} public void remove() {..} } --------------------------------------------------------------------------------- private class ListItr extends Itr implements ListIterator { //這里繼承又實現(xiàn)。 ListItr(int index) { cursor = index; } public boolean hasPrevious() { return cursor != 0; } public E previous() {...} public int nextIndex() { return cursor; } public int previousIndex() { return cursor-1; } public void set(E e) {... } public void add(E e) {...} }
先到這里吧,下一個主題具體到ArrayList和LinkdedList。gogogo。
文章版權歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/68733.html
摘要:三系列用于保存鍵值對,無論是,還是已棄用的或者線程安全的等,都是基于紅黑樹。是完全基于紅黑樹的,并在此基礎上實現(xiàn)了接口。可以看到,只有紅黑樹,且紅黑樹是通過內(nèi)部類來實現(xiàn)的。 JDK容器 前言 閱讀JDK源碼有段時間了,準備以博客的形式記錄下來,也方便復習時查閱,本文參考JDK1.8源碼。 一、Collection Collection是所有容器的基類,定義了一些基礎方法。List、Se...
摘要:集合中成員很豐富,常用的集合有,,等。實現(xiàn)接口的集合主要有。集合中不能包含重復的元素,每個元素必須是唯一的。而以作為實現(xiàn)的構造函數(shù)的訪問權限是默認訪問權限,即包內(nèi)訪問權限。與接口不同,它是由一系列鍵值對組成的集合,提供了到的映射。 原文地址 Java集合 Java集合框架:是一種工具類,就像是一個容器可以存儲任意數(shù)量的具有共同屬性的對象。 Java集合中成員很豐富,常用的集合有Arra...
前言 聲明,本文使用的是JDK1.8 從今天開始正式去學習Java基礎中最重要的東西--->集合 無論在開發(fā)中,在面試中這個知識點都是非常非常重要的,因此,我在此花費的時間也是很多,得參閱挺多的資料,下面未必就做到日更了... 當然了,如果講得有錯的地方還請大家多多包涵并不吝在評論去指正~ 一、集合(Collection)介紹 1.1為什么需要Collection Java是一門面向?qū)ο蟮恼Z言,...
摘要:加載因子是哈希表在其容量自動增加之前可以達到多滿的一種尺度。當哈希表中的條目數(shù)超出了加載因子與當前容量的乘積時,則要對該哈希表進行操作即重建內(nèi)部數(shù)據(jù)結構,從而哈希表將具有大約兩倍的桶數(shù)。成員變量每個對由封裝,存在了對象數(shù)組中。 雖是讀書筆記,但是如轉(zhuǎn)載請注明出處 http://segmentfault.com/blog/exploring/ .. 拒絕伸手復制黨 LinkedLis...
閱讀 3424·2021-11-25 09:43
閱讀 2307·2021-09-06 15:02
閱讀 3548·2021-08-18 10:21
閱讀 3347·2019-08-30 15:55
閱讀 2354·2019-08-29 17:06
閱讀 3539·2019-08-29 16:59
閱讀 971·2019-08-29 13:47
閱讀 2769·2019-08-26 13:24