[JDK] JDK source code analysis -Collection

Java collections framework (Java Collections Framework, JCF) usually contains many common development class, e.g. List, Set, ArrayList, HashMap, HashSet the like, so here intends to start to start.

 

The Collection interface is the root interface in the collection hierarchy, the most commonly used List and Set interfaces inherit from it. Their inheritance structure below (common part):

 

Collection interface methods are described below:

 

Many methods can see the name to know Italian, a brief analysis here:

1. size) (: the number of elements included in the collection;

2. isEmpty (): whether the collection is empty;

3. contains (Object): if an object contained in the collection;

4. iterator (): returns an iterator for the collection, for (sequential) traversing the set;

5.1 Object [] toArray (): the elements of a set "copy" Object to an array;

5.2 T [] toArray (T [] a): 5.1 with the effect, except that the method may specify the type of the array (two methods for switching between a set of arrays);

6. add (E): an additive element;

7. remove (Object): removing element;

8. containsAll (<?> Collection): determining whether the collection contains another set;

9. addAll (<? Extends E> Collection): all the elements of another set are added to the collection;

10. removeAll (Collection <?>): Removes the specified set of all the elements from the set;

11. removeIf (<? Super E> Predicate): removing a specified condition from the set of elements, wherein the functional operation Predicate JDK 1.8 is introduced, i.e., a parameter is passed method;

12. retainAll (<?> Collection): Specifies the retention elements in the set, i.e., it does not remove all of the elements contained in the specified set;

13. clear(): 清空集合;

14. equals(Object): 比较该集合与指定的对象是否相等;

15. hashCode(): 返回该集合的哈希值,注意重写 equals 方法时必须要重写该方法,以满足 Object.hashCode 方法的规定。

16. spliterator(): 可分割迭代器,用于并行遍历集合中的元素(iterator() 方法是顺序遍历);

17. stream() & parallelStream(): JDK 1.8 引入的流(Stream)式数据处理,分别表示串行流和并行流,该部分以后单独分析。

 

此外,还有一个继承自 Iterable 接口的 forEach(Consumer<? super T>) 方法,该方法也是 JDK 1.8 引入的,提供遍历集合元素的函数式操作。

 

PS: JDK 版本如下

 

阅读源码时,个人以为应该先读接口类,而非具体的实现类。原因有二:

 

1. 接口类本身就有协议或标准的性质,至于它的多个实现类,都是对该标准的详细实现。因此,如果熟悉了「标准」,再去研究其实现类会更容易理解。

 

2. 从代码量看,接口类代码较少。实现类的代码一般较多,如果初读源码就钻到实现类,可能容易被搞蒙。

 

Stay hungry, stay foolish.

PS: 本文首发自微信公众号。

Guess you like

Origin www.cnblogs.com/jaxer/p/11105412.html